可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
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
When the MySQL-processing is done one should close the connection. Now I was wondering: Is it sufficient to close the connection bydoing
connection.close()
or do I have to close the cursor first and then the connection? Like this:
cursor.close() connection.close()
回答1:
Think less. Use tools more.
from contextlib import closing with closing( connection.cursor() ) as cursor: ... use the cursor ... # cursor closed. Guaranteed. connection.close()
回答2:
Closing the cursor as soon as you are done with it is probably the best bet, since you have no use for it anymore. However, I haven't seen anything where it's harmful to close it after the db connection. But since you can set it as:
cursor = conn.cursor()
I recommend closing it before, in case you accidentally assign it again and the DB connection is closed as this would throw an error. So you may want to close it first in order to prevent an accidental reassignment with a closed connection.
(Some don't even close it at all though as it gets collected by the garbage collector (see:In Python with sqlite is it necessary to close a cursor?))
References: When to close cursors using MySQLdb
In Python with sqlite is it necessary to close a cursor?
回答3:
Closing a connection should be good enough here in this particular context. If you are working with multiple cursors etc. you need to care about proper resource management.