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 the `with` statement!!
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.
连接具有PEP-249(Python数据库API规范v2.0)中指定的^{} 方法:
由于
pyodbc
connection和cursor都是上下文管理器,现在将其编写为:有关为何不调用conn.close()的解释,请参见https://github.com/mkleehammer/pyodbc/issues/43。
注意,与原始代码不同,这会导致调用
conn.commit()
。使用外部with
语句控制何时要调用commit
。还要注意,无论是否使用
with
语句,每个the docs同样地for cursors(我的重点是):
您可以将整个连接包装在上下文管理器中,如下所示:
然后在需要数据库连接时执行以下操作:
当您离开with块时,连接将关闭。如果发生异常或未使用
with open_db_connection("...", commit=True)
打开块,则此操作也将回滚事务。您可以尝试关闭池,这是默认启用的。有关详细信息,请参见this讨论。
相关问题 更多 >
编程相关推荐