Python Forum

Full Version: Connect and disconnect to database
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I can't seem to find straight answer in the books I've got or from my DDG searches...

When should I connect and disconnect to my database?

Is it OK/acceptable to connect at the beginning of a method and disconnect at the end or should I connect and disconnect each time I want to do something with the database?

I'm just wondering what the norm is!

Thank you
Connection is much more expensive than other DB operations. Unless you are somehow processing jobs from different DB entities (like switching users for some reason), I'd expect to connect at the beginning of the program and use that connection throughout.

Connections are the time when you process the DB server, the specific database, the DB user. If none of those things are changing, I wouldn't bother with a different connection.
Oh wow... that certainly makes things easier! It will probably remove a good number of lines from my code too!

Thank you
And it will be faster. One thing to be careful about - make sure all errors and exceptions are handled and that you close the database connection before the program exits.