开发者

PHP::PDO opening/closing connections multiple times

Lets say I've got a function that makes calls to PHP::PDO, the function opens a connec开发者_JAVA技巧tion, runs the MySQL, closes the connection, returns some data.

I haven't seen any serious problems with this, but is there any reason why this is a bad practice? What are the risks of doing this?


No risks that I'm aware of, but there is network lag for establishing connections. It will likely work fine now when you are just connecting to localhost, but your application will probably have scaling issues if you're establishing multiple connections for each HTTP request and you ever want to move to a secondary database server for whatever reason.

A PHP page is inherently single-threaded, so unless you are starting up multiple threads yourself then there's no (extra) concurrency issues. It's still a good idea to use InnoDB and SQL transactions to help prevent concurrency issues across multiple requests.


There's a fair amount of overhead involved with opening and closing the connection multiple times. It isn't really a that big a deal until it becomes a performance problem. If it does become a problem, you will want to modify it to keep the connection open for the duration of the script and reuse the same connection for multiple database transactions. That's a fairly common practice.

If you do not have a fixed (and small) number of database transactions per script, I would recommend against connecting and tearing down the connection on each action. Instead open it once and hold the connection until the script terminates.


As long as you do not have more queries to run, I do not see this as an issue.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜