我有一个连接到多个数据库(Oracle,MySQL和MSSQL)的脚本,每次运行脚本时都不会使用每个数据库连接,但所有数据库连接都可以在单个脚本执行中使用。我的问题是,“在脚本开头连接所有数据库是否更好,即使可能没有使用所有连接。或者根据需要连接到它们更好,唯一的问题是我需要在循环中进行连接调用(因此数据库连接在循环中将是新的X次)。
是示例代码#1:
// Connections at the beginning of the script
$dbh_oracle = connect2db();
$dbh_mysql = connect2db();
$dbh_mssql = connect2db();
for ($i=1; $i<=5; $i++) {
// NOTE: might not use all the connections
$rs = queryDb($query,$dbh_*); // $dbh can be any of the 3 connections
}
是示例代码#2:
// Connections in the loop
for ($i=1; $i<=5; $i++) {
// NOTE: Would use all the connections but connecting multiple times
$dbh_oracle = connect2db();
$dbh_mysql = connect2db();
$dbh_mssql = connect2db();
$rs_oracle = queryDb($query,$dbh_oracle);
$rs_mysql = queryDb($query,$dbh_mysql);
$rs_mssql = queryDb($query,$dbh_mssql);
}
现在我知道你可以使用持久连接,但是这也是为循环中的每个数据库打开的一个连接吗?与mysql_pconnect(),mssql_pconnect()和adodb for Oracle persistent connection method一样。我知道持久连接也可能是资源匮乏,因为我正在寻找最佳性能/实践。
上的好文章答案 0 :(得分:15)
使用延迟连接包装类:
class Connection
{
private $pdo;
private $dsn;
public __construct($dsn)
{
$this->dsn = $dsn;
}
public query($sql)
{
//the connection will get established here if it hasn't been already
if (is_null($this->pdo))
$this->pdo = new PDO($this->dsn);
//use pdo to do a query here
}
}
我希望你已经在使用PDO了。如果不是,你应该是。 PDO与数据库无关。如果使用过程函数执行此操作,则必须为每种数据库类型创建一个新类。
无论如何,这只是一个骨架(例如,您想在$params
中添加query()
选项),但您应该能够理解。只有在您致电query()
时才会尝试连接。构造对象不会建立连接。
另外,请考虑使用Doctrine。它有懒惰的连接,一般来说生活更轻松。
答案 1 :(得分:2)
最佳性能/实践规则很简单:只连接到一个数据库。
至于连接 - 尝试实现一些数据库访问类。哪个可以按需自动连接。