PHP & PDO: One Connection vs More-than-one Connections

有些话、适合烂在心里 提交于 2019-12-24 00:16:01

问题


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;

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?

Thanks!


回答1:


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.




回答2:


Unless your pages take a huge amount of time to run (huge being relative), then there's no point in relinquishing a connection. You'll end up wasting more cycles on connectiong/disconnecting than you do actually executing queries. MySQL's pretty lightweight as far as connections go, but it still adds up.



来源:https://stackoverflow.com/questions/5130720/php-pdo-one-connection-vs-more-than-one-connections

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!