Where and when to open a database connection

前端 未结 4 1245
無奈伤痛
無奈伤痛 2021-02-07 11:31

I am working on implementing use of the mysql class found here in an existing script. The script almost always needs to interact with the database, even if there are times when

4条回答
  •  面向向阳花
    2021-02-07 11:37

    If your code is performance-sensitive, then the preferred technique tends to be to use some form of connection pooling and/or persistent processes so that you can open one database connection and then use that connection to service many page requests rather than opening a new connection for each request that needs one.

    If your code is not performance-sensitive, then it doesn't really matter anyhow.

    Either way, the exact timing of when the database is accessed in the course of handling a specific request isn't that great of a cause for concern.

    My personal practice is to open a database connection immediately when a new handler process is spawned, then verify that it's still alive when I start processing each request. The rest of the code is then free to just assume that the connection is available when needed without incurring the cost of connecting while a user is waiting for a response.

提交回复
热议问题