我有一个用 PHP 编写的类,用于与我的网站数据库进行通信。我也在编写一个 Java 应用程序,它也将与数据库通信。我想知道是否可以使用相同的结构,但将其转换为 java,如果我这样做,是否有任何问题需要考虑。这是我的php类...
<?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;
}
}
?>