Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What happens if you don't close a pyodbc connection?

Tags:

python

sql

pyodbc

Just wondering what happens if a connection is not properly closed in pyodbc.

Also, do i need to close the cursor before the connection?

In my particular use case I included a call to close the connection in a custom DB Class in the .__del__() method, but do not explicitly call close.

What's best practice?

like image 230
mwoods Avatar asked Jun 18 '15 03:06

mwoods


People also ask

Do I need to close connection Pyodbc?

If you have multiple references to the connection, definitely close it.

What happens if you don't close SQL connection Python?

Our databases have a 300-second (5-minute) timeout on inactive connections. That means, if you open a connection to the database, and then you don't do anything with it for 5 minutes, then the server will disconnect, and the next time you try to execute a query, it will fail.

Is it necessary to close database connection in Python?

If the connection to a database is closed by the user with the close() method, any outstanding transactions are rolled back by the DB. However, instead of depending on any of DB lower level implementation details, your application would be better off calling commit or rollback explicitly.

What is the default timeout for Pyodbc?

By default, such connections appear to timeout after 255 seconds - is there a way to set a shorter timeout?


1 Answers

Connections (and their associated cursors) are automatically closed when they are deleted, so it cleans up behind itself. However, if you're connecting in more than one place, you'll want to close explicitly. Also, to be more Pythonic, it is always better to be explicit.

Also note: closing a connection without committing your changes will result in an automatic implicit rollback.

For more, and reference:

https://github.com/mkleehammer/pyodbc/wiki/Connection#close

like image 190
FlipperPA Avatar answered Sep 20 '22 05:09

FlipperPA