October 13, 2024

Connect SQLite with Python

SQLite is a lightweight, disk-based database that doesn’t require a separate server process. It’s an ideal database for small projects, embedded systems, or as a database for testing. Python provides a built-in module, sqlite3, to connect to SQLite databases and perform various database operations.

1. Prerequisites

Since sqlite3 is a built-in Python module, there is no need to install any additional libraries. Ensure that you have Python installed on your system.

2. Connecting to an SQLite Database

You can connect to an SQLite database using the sqlite3.connect() method. If the database file specified in the connection string does not exist, SQLite will create a new database file.

2.1. Example: Connecting to an SQLite Database

import sqlite3
from sqlite3 import Error

def create_connection(db_file):
    """Create a database connection to the SQLite database specified by db_file"""
    connection = None
    try:
        connection = sqlite3.connect(db_file)
        print(f"Connected to SQLite database: {db_file}")
    except Error as e:
        print(f"Error: {e}")
    return connection

# Connect to the SQLite database (or create it if it doesn't exist)
connection = create_connection("mydatabase.db")

This script connects to an SQLite database named mydatabase.db. If the database file does not exist, SQLite will create it. If the connection is successful, a confirmation message is printed.

3. Performing Basic Database Operations

Once connected to the SQLite database, you can perform various operations such as creating tables, inserting data, querying data, and updating records.

3.1. Example: Creating a Table

You can create a new table in the SQLite database using the CREATE TABLE SQL statement.

def create_table(connection):
    """Create a table in the SQLite database"""
    try:
        cursor = connection.cursor()
        cursor.execute("""
        CREATE TABLE IF NOT EXISTS users (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            name TEXT NOT NULL,
            email TEXT NOT NULL UNIQUE
        )
        """)
        print("Table 'users' created successfully")
    except Error as e:
        print(f"Error: {e}")

# Create a table in the connected database
create_table(connection)

This script creates a table named users in the SQLite database with three columns: id (an auto-incrementing primary key), name (a TEXT field), and email (a TEXT field with a UNIQUE constraint).

3.2. Example: Inserting Data

You can insert data into an SQLite table using the INSERT INTO SQL statement.

def insert_user(connection, user):
    """Insert a new user into the users table"""
    try:
        cursor = connection.cursor()
        cursor.execute("INSERT INTO users (name, email) VALUES (?, ?)", user)
        connection.commit()
        print("User inserted successfully")
    except Error as e:
        print(f"Error: {e}")

# Insert a user into the 'users' table
insert_user(connection, ("Alice Smith", "alice@example.com"))

This script inserts a new record into the users table. The insert_user() function takes a tuple representing the user’s name and email and inserts it into the table.

3.3. Example: Querying Data

You can query data from an SQLite table using the SELECT SQL statement.

def query_users(connection):
    """Query all users from the users table"""
    try:
        cursor = connection.cursor()
        cursor.execute("SELECT * FROM users")

        rows = cursor.fetchall()

        print("Querying all users:")
        for row in rows:
            print(row)
    except Error as e:
        print(f"Error: {e}")

# Query all users from the 'users' table
query_users(connection)

This script queries all records from the users table and prints each record to the console.

3.4. Example: Updating Data

You can update data in an SQLite table using the UPDATE SQL statement.

def update_user_email(connection, user_id, new_email):
    """Update a user's email in the users table"""
    try:
        cursor = connection.cursor()
        cursor.execute("UPDATE users SET email = ? WHERE id = ?", (new_email, user_id))
        connection.commit()
        print("User email updated successfully")
    except Error as e:
        print(f"Error: {e}")

# Update the email of a user with id 1
update_user_email(connection, 1, "new_email@example.com")

This script updates the email address of the user with id 1 in the users table.

3.5. Example: Deleting Data

You can delete data from an SQLite table using the DELETE SQL statement.

def delete_user(connection, user_id):
    """Delete a user from the users table"""
    try:
        cursor = connection.cursor()
        cursor.execute("DELETE FROM users WHERE id = ?", (user_id,))
        connection.commit()
        print("User deleted successfully")
    except Error as e:
        print(f"Error: {e}")

# Delete the user with id 1 from the 'users' table
delete_user(connection, 1)

This script deletes the user with id 1 from the users table.

4. Handling Errors

It’s important to handle potential errors during SQLite operations, such as connection issues or SQL syntax errors. Use try-except blocks to catch and handle these errors gracefully.

4.1. Example: Handling SQLite Errors

import sqlite3
from sqlite3 import Error

def create_connection(db_file):
    """Create a database connection to the SQLite database specified by db_file"""
    connection = None
    try:
        connection = sqlite3.connect(db_file)
        print(f"Connected to SQLite database: {db_file}")
    except Error as e:
        print(f"Error: {e}")
    return connection

def create_table(connection):
    """Create a table in the SQLite database"""
    try:
        cursor = connection.cursor()
        cursor.execute("""
        CREATE TABLE IF NOT EXISTS users (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            name TEXT NOT NULL,
            email TEXT NOT NULL UNIQUE
        )
        """)
        print("Table 'users' created successfully")
    except Error as e:
        print(f"Error: {e}")

# Connect to the SQLite database and create a table
connection = create_connection("mydatabase.db")
if connection is not None:
    create_table(connection)

This script connects to an SQLite database and creates a table, handling any errors that occur during the process.

5. Closing the Database Connection

Always close the database connection after completing your operations to free up resources.

5.1. Example: Closing the Connection

def close_connection(connection):
    """Close the database connection"""
    if connection:
        connection.close()
        print("SQLite connection closed")

# Close the database connection
close_connection(connection)

This script closes the connection to the SQLite database.

Conclusion

Connecting to and interacting with an SQLite database using Python is straightforward with the built-in sqlite3 module. By following the steps outlined in this guide, you can connect to your SQLite database, perform basic database operations, and handle potential errors effectively. Proper error handling and closing the connection after use will help you maintain a robust and efficient database environment.