Q:

Where and when to open a database connection

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 it does not. What is the best practice in this case? Should I open a connection and keep that open until the end of the script or should I open a connection when I need one, closing it when I'm done, to avoid opening a connection when the script does not need it?

A:

Because connections are rather expensive, as others have pointed out, I'd recommend using a "lazy connect" technique in your database layer.  If you have structured your application effectively, your application logic should not be concerned with when connections are opened and closed as this would be encapsulated in the database layer.  The database layer, when asked to perform a query, would first check to see if it has an active connection and if not, create one.  This way you'll avoid opening connections that are never used and you'll also have a nice separation of logic between your application and the database code.

