w3resource

How to use SQLite with SQLAlchemy for Python Database Operations


Integrating SQLite with SQLAlchemy: A Comprehensive Guide

SQLAlchemy is a powerful Python library that provides a high-level Object-Relational Mapping (ORM) system for interacting with databases. SQLite, being a lightweight and self-contained database, pairs seamlessly with SQLAlchemy for database management tasks. This combination allows developers to work with SQLite databases using Python objects and classes, reducing the need for raw SQL queries.

What is SQLAlchemy?

SQLAlchemy is a Python toolkit that provides:

  • ORM to map database tables to Python objects.
  • Core functionality for writing database-agnostic SQL queries.

Using SQLAlchemy with SQLite enables developers to:

  • Create, query, and manage SQLite databases through Python objects.
  • Write clean and maintainable database code.
  • Use SQLAlchemy's ORM features for mapping classes to database tables.

Setting Up SQLite with SQLAlchemy

Step 1: Install SQLAlchemy

Ensure you have Python installed. Then, use pip to install SQLAlchemy.

pip install sqlalchemy

Step 2: Basic Syntax for SQLite Connection

SQLAlchemy uses a connection string to connect to an SQLite database. The syntax for connecting to an SQLite database is:

from sqlalchemy import create_engine

# Create an SQLite connection
engine = create_engine('sqlite:///database_name.db')
  • Replace database_name.db with the desired database name.
  • If the file doesn't exist, SQLAlchemy will create it.

Examples and Code

1. Create an SQLite Database and Table

This example demonstrates how to create a database and define tables using SQLAlchemy ORM.

Code:

# Import required modules
from sqlalchemy import create_engine, Column, Integer, String
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker

# Define a base class for ORM
Base = declarative_base()

# Define the SQLite connection
# Create or connect to a database named 'example.db'
engine = create_engine('sqlite:///example.db', echo=True)

# Define a model (table structure)
class User(Base):
    __tablename__ = 'users'  # Table name in the database

    id = Column(Integer, primary_key=True)  # ID column (Primary Key)
    name = Column(String)  # Name column (String type)
    age = Column(Integer)  # Age column (Integer type)

# Create all tables in the database
Base.metadata.create_all(engine)  # Generates the 'users' table in the database

Explanation:

  • Base: Serves as the foundation for defining table schemas.
  • User: Maps the users table to a Python class.
  • create_all(engine): Creates the defined tables in the database.

2. Insert Data into the Database

This example shows how to insert data using a session.

Code:

# Create a session for database operations
Session = sessionmaker(bind=engine)  # Bind the session to the engine
session = Session()  # Initialize the session

# Add a new user to the database
new_user = User(name='Alice', age=25)  # Create a new User object
session.add(new_user)  # Add the new user to the session
session.commit()  # Commit the changes to the database

Explanation:

  • A session is used to manage database operations.
  • session.add(): Adds an object to the session.
  • session.commit(): Saves the changes to the database.

3. Query Data from the Database

This example demonstrates how to retrieve data from the database.

Code:

# Query all users
users = session.query(User).all()  # Fetch all rows from the 'users' table

# Display user details
for user in users:
    print(f"ID: {user.id}, Name: {user.name}, Age: {user.age}")

Explanation:

  • session.query(User).all(): Fetches all records from the users table.
  • The for loop iterates over the results and prints each record's details.

4. Update Data in the Database

This example demonstrates how to update a record.

Code:

# Fetch a user by ID
user_to_update = session.query(User).filter_by(id=1).first()  # Get the user with ID 1

if user_to_update:  # Check if the user exists
    user_to_update.age = 30  # Update the age
    session.commit()  # Save the changes

Explanation:

  • filter_by(id=1): Filters records based on the condition (id=1).
  • first(): Returns the first matching record.

5. Delete Data from the Database

This example demonstrates how to delete a record.

Code:

# Fetch a user by ID
user_to_delete = session.query(User).filter_by(id=1).first()  # Get the user with ID 1

if user_to_delete:  # Check if the user exists
    session.delete(user_to_delete)  # Mark the record for deletion
    session.commit()  # Save the changes

Explanation:

  • session.delete(): Marks a record for deletion.
  • session.commit(): Permanently removes the record from the database.

Advantages of Using SQLite with SQLAlchemy

    1. Simplified Database Management: SQLAlchemy's ORM abstracts complex SQL queries.

    2. Cross-Platform Compatibility: SQLite and SQLAlchemy work seamlessly across platforms.

    3. Enhanced Readability: Pythonic code enhances code readability and maintainability.

    4. Scalability: SQLAlchemy supports switching databases (e.g., MySQL, PostgreSQL) with minimal changes.

Practical Guides to SQLite Snippets and Examples.



Follow us on Facebook and Twitter for latest update.