Is there any difference between closing a cursor or a connection in SQLite?

百般思念 提交于 2019-12-07 09:01:19

问题


I have been using always the command cur.close() once I'm done with the database:

import sqlite3

conn = sqlite3.connect('mydb')
cur = conn.cursor()
# whatever actions in the database
cur.close()

However, I just saw in some cases the following approach:

import sqlite3

conn = sqlite3.connect('mydb')
cur = conn.cursor()
# whatever actions in the database
cur.close()
conn.close()

And in the official documentation sometimes the cursor is closed, sometimes the connection and sometimes both.

My questions are:

  1. Is there any difference between cur.close() and conn.close()?
  2. Is it enough to close one, once I am done (or I must close both)? If so, which one is preferable?

回答1:


[On closing cursors]

If you close the cursor, you are simply flagging it as invalid to process further requests ("I am done with this").

So, in the end of a function/transaction, you should keep closing the cursor, giving hint to the database that that transaction is finished.

A good pattern is to make cursors are short-lived: you get one from the connection object, do what you need, and then discard it. So closing makes sense and you should keep using cursor.close() at the end of your code section that makes use of it.

I believe (couldn't find any references) that if you just let the cursor fall out of scope (end of function, or simply del cursor) you should get the same behavior. But for the sake of good coding practices you should explicitly close it.

[Connection Objects]

When you are actually done with the database, you should close your connection to it. that means connection.close()



来源:https://stackoverflow.com/questions/39616077/is-there-any-difference-between-closing-a-cursor-or-a-connection-in-sqlite

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