![mdb数据库连接代码](https://img-blog.csdnimg.cn/img_convert/031676ae60b5d9885459ef200eb52f5a.png)
mdb数据库连接代码
This is a follow up to a question posted by Sam in my DB-2-MDB2 post. The question was if you can reuse an exisitng database connection you've already established and not have MDB2 creating a second connection.
这是Sam在我的DB-2-MDB2帖子中发布的一个问题的跟进。 问题是,是否可以重用已经建立的现有数据库连接,而没有让MDB2创建第二个连接。
使用非持久连接时 (When using a non-persistent connection)
No worries in this case. No new connection will be established. As the PHP manual states:
在这种情况下不用担心。 不会建立新的连接。 如PHP手册所述:
If a second call is made to mysql_connect() with the same arguments, no new link will be established, but instead, the link identifier of the already opened link will be returned.
如果使用相同的参数再次调用mysql_connect(),则不会建立新的链接,但是将返回已打开的链接的链接标识符。
That is, if you don't set the fourth parameter to mysql_connect()
to true
. This parameter forces a new connection. BTW, in MDB2 if you do want to force a new connection, you have to set new_link
in the DSN string to true
也就是说,如果您没有将第四个参数mysql_connect()
为true
。 此参数强制建立新连接。 顺便说一句,在MDB2如果你想强制一个新的连接,你必须设置new_link
在DSN字符串来true
Bottom line, if you don't do anything special, the existing connection will be reused by MDB2. You can always verify that this is the case by calling phpinfo(INFO_MODULES);
and looking in the "mysql" section.
最重要的是,如果您没有做任何特别的事情,MDB2将重用现有的连接。 您始终可以通过调用phpinfo(INFO_MODULES);
验证这种情况phpinfo(INFO_MODULES);
并查看“ mysql”部分。
使用持久连接时 (When using a persistent connection)
When using a persistent connection you have to do some additional steps to ensure that the same persistent connection is used by MDB2.
使用持久连接时,您必须执行一些附加步骤以确保MDB2使用相同的持久连接。
Tell MDB2 that you want a persistent connection -
$mdb2->setOption('persistent', true);
告诉MDB2您需要持久连接-
$mdb2->setOption('persistent', true);
Tell MDB2 which connection you want to use -
$mdb2->connection = $link;
, where$link
is your existing connection告诉MDB2您要使用哪个连接-
$mdb2->connection = $link;
,其中$link
是您现有的连接Set
$mdb2->opened_persistent = true;
设置
$mdb2->opened_persistent = true;
Here's an example:
这是一个例子:
<?php
// somewhere you've established a connection
$link = mysql_pconnect('localhost', 'root', '');
mysql_select_db('test', $link);
echo $link; // e.g. Resource id #5
// Create MDB2 object
require_once 'MDB2.php';
$dsn = 'mysql://root@localhost/test';
$mdb2 =& MDB2::factory($dsn);
// reuse your connection
$mdb2->setOption('persistent', true);
$mdb2->opened_persistent = true;
$mdb2->connection = $link;
// connect
$mdb2->connect();
echo $mdb2->connection; // Resource id #5
// check the "mysql" part to be sure
phpinfo(INFO_MODULES);
?>
Tell your friends about this post on Facebook and Twitter
在Facebook和Twitter上告诉您的朋友有关此帖子的信息
翻译自: https://www.phpied.com/reusing-an-existing-database-connection-with-mdb2/
mdb数据库连接代码