我为每个数据库表对象都有一个类。每个类负责连接/查询/数据格式(数据库表特定逻辑),因为我更喜欢为每个类分配连接以获得更好的模块性。此外,我正在为某些表和查询使用特定连接。
我的问题是如何检查连接是否已经存在以便它不会启动另一个连接?
基本上我想检查是否已经建立了具有相同用户名/密码/数据库的连接。或者这不是必需的,因为mySql不会为同一个用户启动新连接?如果是这样,请解释。
经过进一步的研究发现这是不可能的......它需要获取线程ID并使用带有线程ID的conn,它将像一个持久的conn;或者它需要跟踪脚本中使用的每个线程ID,这有点无用。
还没有一种简单的方法可以做到这一点......持久连接可以是一个选择,但是你必须处理连接清理并再次sux:)
P.S。 :最终我在我的应用程序运行期间为连接创建了一个跟踪系统(那些说它们存储在全局可用对象中的人我们是对的)。在单例类对象中的2个数组中存储conn对象和conn params,检查params是否已经存在于params数组中,如果不是则创建新的conn,如果是,则从数组键中获取conn对象与params中的键相同被发现......我已经为此做了一个架构但是不想使用那个类...不是我开始的逻辑:),而且还想把它放在一个库项目中,这就是为什么我在寻找一个简单而抽象的解决方案,但只有一个特定的解决方案:)
答案 0 :(得分:0)
我建议您阅读此内容 - 我认为这会对您有所帮助http://www.php.net/manual/en/features.persistent-connections.php
答案 1 :(得分:0)
如果每个类必须具有不同的连接,则可以使用静态类属性来保存连接,并使用单例模式来检索它。
class SomeTable {
// Connection resource as a static property
// Since it is static, it will be shared by all instances of class SomeTable
public static $db = FALSE;
// Static method to retrieve the connection
// or create it if it doesn't exist
public static function get_conn() {
if (self::$db) {
// Just return the connection if it already exists
return self::$db;
}
else {
// If it doesn't already exist, create it and return it
self::$db = mysql_connect(...);
return self::$db;
}
}
// In other methods, use self::get_conn()
public function someQuery() {
$sql = "SELECT col FROM tbl";
// Call the connection singleton explicitly
// as the second param to mysql_query()
$result = mysql_query($sql, self::get_conn());
}
}
答案 2 :(得分:0)
too may connections
错误。我建议使用单例模式和一些OO。
class Singleton{
private static $instance=null;
public function connection(){
if(self::$instance==null){
self::$instance = mysql_connect(); // define it in your way,
}
return self::$connection;
}
}
class TableA extends Singleton{
function find($id){
$query="select * from `A` where `id`='$id'";
mysql_query($query, $this->connection());
... // other codes
}
}