Python sqlite3: How to establish/close a connection

Updated: February 6, 2024 By: Guest Contributor Post a comment

Introduction

In the world of Python, managing databases is a quintessential skill for any developer, especially when dealing with small to medium-sized applications. SQLite, with its lightweight disk-based database, makes it an ideal choice for applications needing a self-contained, serverless, zero-configuration, transactional SQL database engine. Python provides built-in support for SQLite through the sqlite3 module, making it incredibly straightforward to connect to and interact with SQLite databases. In this tutorial, we’ll explore how to establish and close connections to an SQLite database using Python’s sqlite3 module, along with delving into some advanced features.

Establishing a Connection

Before you can interact with an SQLite database, you must first establish a connection. This is done using the sqlite3 module’s connect function, which returns a Connection object.

import sqlite3
# Connect to the database, creating it if it doesn\'t exist
db = sqlite3.connect('example.db')

This creates (or opens, if it already exists) an SQLite database named ‘example.db’ in your current working directory. The connection object resulting from this operation is essential for executing SQL commands through Python.

Closing the Connection

If you don’t to perform more database operations, it’s important to close your connection. Failing to close the connection properly can lead to memory leaks and other unwanted behaviors.

db.close()

The close method on the connection object ensures that all resources are freed and the connection is properly closed.

Executing Queries

With your connection established, you can now execute SQL queries.

cursor = db.cursor()
cursor.execute('''CREATE TABLE IF NOT EXISTS inventory (item_id INTEGER PRIMARY KEY, name TEXT, quantity INTEGER)''')
db.commit()

This code snippet creates a table named ‘inventory’ if it doesn’t already exist, with columns for item ID, name, and quantity. The commit method finalizes the changes.

Inserting Data

Inserting data into your newly created table is straightforward.

cursor.execute('''INSERT INTO inventory (name, quantity) VALUES ('Apple', 100), ('Banana', 150)''')
db.commit()

Here, we insert two rows into the ‘inventory’ table. It’s vital to commit your changes to ensure they are saved to the database.

Querying Data

To retrieve data, you can execute a SELECT statement and then iterate over the results.

cursor.execute('''SELECT * FROM inventory''')
for row in cursor.fetchall():
    print(row)

This will print all rows in the ‘inventory’ table.

Advanced Features

Beyond basic CRUD (Create, Read, Update, Delete) operations, sqlite3 offers several advanced features.

Using Transactions

SQLite supports database transactions. A transaction is a sequence of operations performed as a unit. In sqlite3, transactions are managed with the commit and rollback methods.

try:
    cursor.execute('''UPDATE inventory SET quantity = quantity - 25 WHERE name = 'Apple' ''')
    db.commit()
except sqlite3.Error:
    db.rollback()

This updates the quantity of ‘Apple’ and commits the transaction. If an error occurs, the changes are rolled back.

Handling Errors

Handling errors effectively is crucial. sqlite3 provides different exception types for error handling.

try:
    cursor.execute('''INSERT INTO inventory (name, quantity) VALUES (?, ?)''', ('Pear', 80))
    db.commit()
except sqlite3.IntegrityError:
    print('ERROR: Could not insert data.')

This tries to insert data into the database, catching any integrity errors that might occur due to, for example, unique constraint violations.

Conclusion

Python\’s sqlite3 module provides a convenient and efficient way to manage SQLite databases. From establishing connections to executing queries and transactions, it serefs a broad spectrum of database operations. By incorporating proper connection management practices, such as ensuring connections are closed after use, developers can create robust, reliable applications that effectively leverage SQLite databases.