Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Database connection Close

Using the code below leaves me with an open connection, how do I close?

import pyodbc conn = pyodbc.connect('DRIVER=MySQL ODBC 5.1 driver;SERVER=localhost;DATABASE=spt;UID=who;PWD=testest')   csr = conn.cursor()   csr.close() del csr 
like image 411
Merlin Avatar asked Sep 23 '10 23:09

Merlin


People also ask

Do we need to close DB connection in python?

Connections are automatically closed when they are deleted (typically when they go out of scope) so you should not normally need to call [ conn. close() ], but you can explicitly close the connection if you wish. and similarly for cursors (my emphasis):

How do you close a database in Python?

To disconnect Database connection, use close() method. If the connection to a database is closed by the user with the close() method, any outstanding transactions are rolled back by the DB.


1 Answers

Connections have a close method as specified in PEP-249 (Python Database API Specification v2.0):

import pyodbc conn = pyodbc.connect('DRIVER=MySQL ODBC 5.1 driver;SERVER=localhost;DATABASE=spt;UID=who;PWD=testest')   csr = conn.cursor()   csr.close() conn.close()     #<--- Close the connection 

Since the pyodbc connection and cursor are both context managers, nowadays it would be more convenient (and preferable) to write this as:

import pyodbc conn = pyodbc.connect('DRIVER=MySQL ODBC 5.1 driver;SERVER=localhost;DATABASE=spt;UID=who;PWD=testest')  with conn:     crs = conn.cursor()     do_stuff     # conn.commit() will automatically be called when Python leaves the outer `with` statement     # Neither crs.close() nor conn.close() will be called upon leaving the `with` statement!!  

See https://github.com/mkleehammer/pyodbc/issues/43 for an explanation for why conn.close() is not called.

Note that unlike the original code, this causes conn.commit() to be called. Use the outer with statement to control when you want commit to be called.


Also note that regardless of whether or not you use the with statements, per the docs,

Connections are automatically closed when they are deleted (typically when they go out of scope) so you should not normally need to call [conn.close()], but you can explicitly close the connection if you wish.

and similarly for cursors (my emphasis):

Cursors are closed automatically when they are deleted (typically when they go out of scope), so calling [csr.close()] is not usually necessary.

like image 123
unutbu Avatar answered Sep 18 '22 20:09

unutbu