Phi*_*ord 4 php persistence loops database-connection
我有一个连接到多个数据库(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
}
Run Code Online (Sandbox Code Playgroud)
是的示例代码#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);
}
Run Code Online (Sandbox Code Playgroud)
现在我知道你可以使用持久连接,但是这也是循环中每个数据库打开的一个连接吗?像mysql_pconnect(),mssql_pconnect()和adodb for Oracle持久连接方法.我知道持久连接也可能是资源匮乏,因为我正在寻找最佳性能/实践.
这是一篇关于为什么持久连接可能导致问题的好帖子
rye*_*guy 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
}
}
Run Code Online (Sandbox Code Playgroud)
我希望你已经在使用PDO了.如果不是,你应该是.PDO与数据库无关.如果使用过程函数执行此操作,则必须为每种数据库类型创建一个新类.
无论如何,这只是一个骨架(例如,你想要添加一个$params
选项query()
),但你应该能够理解.仅在您致电时尝试连接query()
.构造对象不会建立连接.
另外,请考虑使用Doctrine.它有懒惰的连接,一般来说生活更轻松.