Python MySQLdb:connection.close()VS. cursor.close() [英] Python MySQLdb: connection.close() VS. cursor.close()
本文介绍了Python MySQLdb:connection.close()VS. cursor.close()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果我使用MySQLdb通过Python连接到MySQL-Server.我这样创建connection
和cursor
:
If I use MySQLdb to connect to MySQL-Server through Python. I create a connection
and a cursor
like this:
connection = MySQLdb.connect(...)
cursor = connection.cursor()
# process
完成MySQL处理后,应关闭connection
.现在我想知道:通过执行以下操作来关闭connection
是否足够:
When the MySQL-processing is done one should close the connection
. Now I was wondering: Is it sufficient to close the connection
by doing:
connection.close()
还是我必须先关闭cursor
然后关闭connection
?像这样:
or do I have to close the cursor
first and then the connection
? Like this:
cursor.close()
connection.close()
推荐答案
使用with
,此工具可让您创建一个临时游标,一旦返回到先前的缩进级别,该游标将关闭.
Use with
, this tool allows you to create a temporary cursor that will be closed once you return to your previous indentation level.
from contextlib import closing
with closing( connection.cursor() ) as cursor:
(indented) use the cursor
(non-indented) cursor is closed.
connection.close()
这篇关于Python MySQLdb:connection.close()VS. cursor.close()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文