I have a class written in PHP which I use to communicate with my website databases. I am also writing a Java application which will communicate with a database too. I was wondering if it was possible to use the same structure but convert it to java and are there any issues I would need to consider if I do this. Here is my php class…
<?php
class Database {
private static $instance = null;
private $connection;
private $selected_database;
private $last_query;
public static function getInstance() {
if (self::$instance != null) {
return self::$instance;
} else {
return new self;
}
}
function __construct() {
$this->open_connection();
}
private function open_connection() {
$this->connection = mysql_connect(DB_HOST, DB_USER, DB_PASS);
if (!$this->connection) {
die('Database connection failed: ' . mysql_error());
} else {
$this->selected_database = mysql_select_db(DB_NAME, $this->connection);
if (!$this->selected_database) {
die('Database selection failed: ' . mysql_error());
}
}
}
private function close_connection() {
if (isset($this->connection)) {
mysql_close($this->connection);
unset($this->connection);
}
}
public function query($sql) {
$this->last_query = $sql;
$result = mysql_query($sql, $this->connection);
$this->confirm_query($result);
return $result;
}
private function confirm_query($result) {
if (!$result) {
die('Database query failed: ' . mysql_error() . '<br>Last SQL query: ' . $this->last_query);
}
}
public function escape_value($string) {
return mysql_real_escape_string($string);
}
public function fetch_array($result) {
return mysql_fetch_array($result);
}
public function fetch_assoc($result) {
return mysql_fetch_assoc($result);
}
public function num_rows($result) {
return mysql_num_rows($result);
}
public function insert_id() {
return mysql_insert_id($this->connection);
}
public function affected_rows() {
return mysql_affected_rows($this->connection);
}
public function get_fields_from($table_name) {
$result = $this->query("SHOW COLUMNS FROM `{$this->escape_value($table_name)}`");
$fields = array();
while ($row = $this->fetch_assoc($result)) {
$fields[] = $row['Field'];
}
return $fields;
}
}
?>
No you can create a class in Java, which has a structure, that is nearly like the one above.
or die()is like throwing anException. You should be aware, that there are different ways of returning data from a database in Java and PHP. PHP often uses arrays or assoc-arrays. In Java you will get a “pointer” to the result.You must decide, if you want to transfer the data to an array, because of the memory consumption.