PHP& PDO:一种连接与多于一种连接 [英] PHP & PDO: One Connection vs More-than-one Connections
问题描述
在我的PHP程序中,对于任何给定的网页请求,我都需要在0到3次之间访问数据库.我正在使用PDO与MySQL进行交互.首先,我使用类似这样的方式创建数据库连接:
In my PHP program I need to hit the database between 0 and 3 times on any given webpage request. I am using PDO to interact with MySQL. First I create a database connection using something like this:
$dbh = new PDO("mysql:host=$hostname;dbname=animals", $username, $password);
然后我做我需要做的并关闭连接,如下所示:
Then I do what I need to do and close the connection like this:
$dbh = null;
我现在打开和关闭连接0-3次,与我与MySQL进行交互的次数相同.
I open and close a connection 0-3 times right now, the same number of times I need to interact with MySQL.
我的问题是,我应该重新使用此连接吗?我的查询不是一个接一个的,它们分散在我的程序中,我真的不认为一个接一个地运行它们会很容易.
My question is, should I be re-using this connection instead? My queries are not one after another, they are scattered throughout my program and I don't really think it would be easy to run them one right after another.
那么创建一个新的数据库连接并为每次交互(查询)关闭它还是只打开连接并重用它是更好的选择吗?有什么区别吗?
So is it better to create a new database connection and close it for each interaction (query) or to just leave the connection open and reuse it? Does it make any difference?
谢谢!
推荐答案
对于典型的网站页面,您应该对所有查询重新使用相同的连接.
For a typical website page, you should be reusing the same connection for all queries.
花时间断开和重新连接是不值得的.
It's not worth it to spend time disconnecting and reconnecting.
这篇关于PHP& PDO:一种连接与多于一种连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!