Python MySQLdb: connection.close() VS. cursor.close()

匿名 (未验证) 提交于 2019-12-03 01:29:01

问题:

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.



易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!