Python数据库连接关闭

Python数据库连接关闭

问题描述:

使用下面的代码会使我处于打开状态,该如何关闭?

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


连接具有 close 方法,如PEP-249(Python数据库API规范v2.0 ):

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




由于 pyodbc 连接和光标都是上下文管理器,如今将其写为:


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!! 

请参见 https://github.com/mkleehammer/pyodbc/issues/43 解释为何不调用conn.close()的原因。

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

请注意,与原始代码,这会导致调用 conn.commit()。使用外部 with 语句控制何时调用 commit

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.

还要注意,无论您是否使用 with 语句,每个文档

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


删除连接后,它们会自动关闭(通常在它们超出范围时),因此通常不需要调用[ conn.close()],但可以根据需要显式关闭连接。 / p>

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):


删除光标(通常是超出范围时)会自动关闭, so通常不需要调用[ csr.close()]