Is there any difference between closing a cursor or a connection in SQLite?
<p>I have been using always the command <code>cur.close()</code> once I'm done with the database:</p>

<pre><code>import sqlite3

conn = sqlite3.connect('mydb')
cur = conn.cursor()
# whatever actions in the database
cur.close()
</code></pre>

<p>However, I just saw in some cases the following approach:</p>

<pre><code>import sqlite3

conn = sqlite3.connect('mydb')
cur = conn.cursor()
# whatever actions in the database
cur.close()
conn.close()
</code></pre>

<p>And in the official <a href="https://docs.python.org/2/library/sqlite3.html" rel="nofollow">documentation</a> sometimes the cursor is closed, sometimes the connection and sometimes both.</p>

<p>My question are: </p>

<ol>
<li>Is there any difference between <code>cur.close()</code> and <code>conn.close()</code>?</li>
<li>Is it enough closing one of both once I am done? If so, which one is preferable?</li>
</ol>

<p><em>[On closing cursors]</em></p>

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

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

<p>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.</p>

<p>I <strong>believe</strong> (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.</p>

<p>[Connection Objects]</p>

<p>When you are actually done <em>with the database</em>, you should close your <strong>connection</strong> to it. that means connection.close()</p>

python sqlite sqlite3 cursor