PHP mySQL - When is the best time to disconnect from the database?

前端 未结 6 605
抹茶落季
抹茶落季 2020-12-03 17:08

I use lazy connection to connect to my DB within my DB object. This basically means that it doesn\'t call mysql_connect() until the first query is handed to it, and

6条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-03 17:42

    The basic unit of execution presumably is an entire script. What you first of all are wanting to apply resources (i.e. the database) to, efficiently and effectively, is the entirety of a single script.

    However, PHP, Apache/IIS/whatever, have lives of their own; and they are capable of using the connections you open beyond the life of your script. That's the signficance of persistent (or pooled) connections.

    Back to your script. It turns out you have a great deal of opportunity to be creative about using that connection during its execution.

    The typical naive script will tend to hit the connection again and again, picking up locally appropriate scraps of data associated with given objects/modules/selected options. This is where procedural methodology can inflict a penalty on that connection by opening, requesting, receiving, and closing. (Note that any single query will remain alive until it is explicitly closed, or the script ends. Be careful to note that a connection and a query are not the same thing at all. Queries tie up tables; connections tie up ... connections (in most cases mapped to sockets). So you should be conscious of proper economy in the use of both.

    The most economical strategy with regard to queries is to have as few as possible. I'll often try to construct a more or less complex joined query that brings back a full set of data rather than parceling out the requests in small pieces.

提交回复
热议问题