Sling Academy
Home/SQLite/Using SQLAlchemy to Build SQLite Applications

Using SQLAlchemy to Build SQLite Applications

Last updated: December 07, 2024

SQLAlchemy is a comprehensive and flexible SQL toolkit for Python developers, which can be used for interacting with databases using object-relational mapping (ORM) or direct SQL expression. This article will guide you through using SQLAlchemy to build applications with SQLite, a lightweight and easy-to-use database popular for many use cases.

Getting Started with SQLAlchemy

First, ensure that you have Python installed on your system along with pip, the Python package manager. You can verify this by running the following commands:

python --version
pip --version

If Python is installed, the above commands will return their respective version numbers. Next, install SQLAlchemy using pip:

pip install SQLAlchemy

Setting Up SQLite with SQLAlchemy

SQLite is bundled with Python, so you don't need to install it separately. To connect to a SQLite database using SQLAlchemy, create an engine:

from sqlalchemy import create_engine

# Create an SQLite database 'example.db'
engine = create_engine('sqlite:///example.db', echo=True)

Here, we are creating an engine that interfaces with an SQLite database named example.db. The echo=True parameter makes SQLAlchemy log all SQL statements it executes, which is helpful for debugging.

Defining a Model

To use the ORM feature of SQLAlchemy, define Python classes that map to tables in your database. Each field in the class should correspond to a column in your table:

from sqlalchemy import Column, Integer, String
from sqlalchemy.ext.declarative import declarative_base

Base = declarative_base()

class User(Base):
    __tablename__ = 'users'

    id = Column(Integer, primary_key=True)
    name = Column(String)
    age = Column(Integer)

    def __repr__(self):
        return f"<User(id={self.id}, name={self.name}, age={self.age})>"

Here, the User class is defined as a model, representing a user entity with an ID, name, and age. The __tablename__ attribute specifies the name of the table corresponding to this class.

Creating Tables

With your model defined, create the table in the database:

Base.metadata.create_all(engine)

This command instructs SQLAlchemy to create all tables that don't exist in the database yet, based on the models defined.

Interacting with the Database

Now that you have a database with a table, you can start interacting with it. To manage transactions, SQLAlchemy uses a Session system. Create a session as follows:

from sqlalchemy.orm import sessionmaker

Session = sessionmaker(bind=engine)
session = Session()

Adding Entries

You can now add new entries to the database:

new_user = User(name='John Doe', age=30)
session.add(new_user)
session.commit()

This code snippet creates a new User instance, adds it to the session, and commits the transaction, saving it to the database.

Querying Entries

To retrieve data, use the query function:

users = session.query(User).all()
for user in users:
    print(user)

This fetches all the users from the database and prints their details.

Updating and Deleting

Updating an entry involves fetching it first, modifying it, and committing the session:

user_to_update = session.query(User).filter_by(name='John Doe').first()
user_to_update.age = 31
session.commit()

To delete an entry:

user_to_delete = session.query(User).filter_by(name='John Doe').first()
session.delete(user_to_delete)
session.commit()

These snippets demonstrate fetching specific users and either updating their details or removing them from the database.

Conclusion

By using SQLAlchemy, interacting with databases such as SQLite becomes simpler and more intuitive for Python developers. This object-oriented method gives us a high level of abstraction and is highly efficient for handling complex data interactions without relying directly on raw SQL. Whether you're building a small application or a large system, SQLAlchemy and SQLite form a robust combination for database management.

Next Article: Best Tools for Data Migration Between SQLite and Enterprise Databases

Previous Article: Migrating Data from SQLite to MySQL or PostgreSQL

Series: SQLite Migration and Integration

SQLite

You May Also Like

  • How to use regular expressions (regex) in SQLite
  • SQLite UPSERT tutorial (insert if not exist, update if exist)
  • What is the max size allowed for an SQLite database?
  • SQLite Error: Invalid Value for PRAGMA Configuration
  • SQLite Error: Failed to Load Extension Module
  • SQLite Error: Data Type Mismatch in INSERT Statement
  • SQLite Warning: Query Execution Took Longer Than Expected
  • SQLite Error: Cannot Execute VACUUM on Corrupted Database
  • SQLite Error: Missing Required Index for Query Execution
  • SQLite Error: FTS5 Extension Malfunction Detected
  • SQLite Error: R-Tree Node Size Exceeds Limit
  • SQLite Error: Session Extension: Invalid Changeset Detected
  • SQLite Error: Invalid Use of EXPLAIN Statement
  • SQLite Warning: Database Connection Not Closed Properly
  • SQLite Error: Cannot Attach a Database in Encrypted Mode
  • SQLite Error: Insufficient Privileges for Operation
  • SQLite Error: Cannot Bind Value to Parameter
  • SQLite Error: Maximum String or Blob Size Exceeded
  • SQLite Error: Circular Reference in Foreign Key Constraints