gpt4 book ai didi

Python 数据库连接 关闭

转载 作者:IT老高 更新时间:2023-10-28 20:38:57 24 4
gpt4 key购买 nike

使用下面的代码会打开一个连接,我该如何关闭?

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)中指定的方法:

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 connectioncursor都是上下文管理器,现在写成这样会更方便(也更可取):

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() 的解释。

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


另外请注意,无论您是否使用 with 语句,根据 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.

同样for cursors (我的重点):

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

关于Python 数据库连接 关闭,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3783238/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com