Where and when to open a database connection

前端 未结 4 1164
無奈伤痛
無奈伤痛 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:45

    Usually you'd only want to open a connection to your database when you need to use that connection. Keeping connections open can increase the chance that part of your code will accidentally, or maliciously through the actions of others, cause unwanted queries to be performed on the database.

    That being the case, you should only open the connection before you want to run your queries. If you have a large number of queries, try to open your connection as late in the process as possible.

    It is better to have one connection left open for a longer duration than to open and close multiple connections.

提交回复
热议问题