Is there any difference between closing a cursor o

2019-05-07 02:51发布

问题:

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()