Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?
like image 866
J0ANMM Avatar asked Oct 18 '22 01:10

J0ANMM


1 Answers

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

like image 85
Cadu Avatar answered Nov 15 '22 06:11

Cadu