Course contentsShow
← Data Science
Lesson 1101 of 2,14528. Working with Databases from PythonFree lesson

Closing Cursors and Connections

Properly clean up database resources using context managers and explicit close() calls.

Closing Cursors and Connections

You'll learn why and how to properly release database resources when you're done with them.

When you open a connection to a database or create a cursor, you're consuming server resources—network sockets, memory buffers, and database sessions. Just like closing a file after reading it, you should always close cursors and connections when you're finished to free up these resources.

Why This Matters

Think of a database connection like checking out a library book. If you never return it, the library can't lend it to anyone else. Similarly, unclosed connections can exhaust a database's connection limit, blocking other users or processes from accessing the data.

Two Ways to Clean Up

1. Explicit close() calls:

import sqlite3

conn = sqlite3.connect('data.db')
cursor = conn.cursor()
cursor.execute("SELECT * FROM users")
results = cursor.fetchall()

cursor.close()  # Close cursor first
conn.close()    # Then close connection

Always close the cursor before closing the connection—cursors depend on the connection being open.

2. Context managers (recommended):

import sqlite3

with sqlite3.connect('data.db') as conn:
    cursor = conn.cursor()
    cursor.execute("SELECT * FROM users")
    results = cursor.fetchall()
    cursor.close()
# Connection automatically closed when leaving the 'with' block

Context managers handle cleanup automatically, even if an error occurs mid-operation—making your code safer and cleaner.

Best Practice

Always use context managers for connections when possible, and explicitly close cursors when you're done fetching results. This prevents resource leaks and keeps your database healthy.

Key Takeaway: Always close cursors and connections to release database resources; use context managers for automatic, safe cleanup.