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
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Connections have a
closemethod as specified in PEP-249 (Python Database API Specification v2.0):Since the
pyodbcconnection and cursor are both context managers, nowadays it would be more convenient (and preferable) to write this as: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 outerwithstatement to control when you wantcommitto be called.Also note that regardless of whether or not you use the
withstatements, per the docs,and similarly for cursors (my emphasis):