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?
If you have multiple references to the connection, definitely close it.
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.
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.
By default, such connections appear to timeout after 255 seconds - is there a way to set a shorter timeout?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With