Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Python with sqlite is it necessary to close a cursor?

Tags:

python

sqlite

Here is the scenario. In your function you're executing statements using a cursor, but one of them fails and an exception is thrown. Your program exits out of the function before closing the cursor it was working with. Will the cursor float around taking up space? Do I have to close the cursor?

Additionally, the Python documentation has an example of cursor use and says: "We can also close the cursor if we are done with it." The keyword being "can," not "must." What do they mean precisely by this?

like image 509
user113946 Avatar asked Feb 24 '10 23:02

user113946


People also ask

What happens if you don't close SQLite connection?

If you leave it open, it stays open until it goes out of scope and garbage collected. At that point it might be safely closed (and I believe sqlite3 does that). But better to be safe than sorry. Close your connections when you will no longer use them.

How does SQLite cursor work?

The sqlite3. Cursor class is an instance using which you can invoke methods that execute SQLite statements, fetch data from the result sets of the queries. You can create Cursor object using the cursor() method of the Connection object/class.

How do you close a cursor in Python?

close() Method. Use close() when you are done using a cursor. This method closes the cursor, resets all results, and ensures that the cursor object has no reference to its original connection object.

When working with SQLite database in Python What is the purpose of a cursor?

Cursor objects allow you to keep track of which result set is which, since it's possible to run multiple queries before you're done fetching the results of the first. Also worth keeping in mind: PEP 249 does not define execute on a connection object, this is an sqlite3 extension.


2 Answers

It's probably a good idea (although it might not matter much with sqlite, don't know there, but it'll make your code more portable). Further, with recent Python (2.5+), it's easy:

from __future__ import with_statement from contextlib import closing  with closing(db.cursor()) as cursor:     # do some stuff 
like image 97
Michael Ekstrand Avatar answered Sep 28 '22 03:09

Michael Ekstrand


You're not obliged to call close() on the cursor; it can be garbage collected like any other object.

But even if waiting for garbage collection sounds OK, I think it would be good style still to ensure that a resource such as a database cursor gets closed whether or not there is an exception.

like image 24
Ben James Avatar answered Sep 28 '22 05:09

Ben James