Sling Academy
Home/SQLite/Using SQLite with Popular ORM Frameworks

Using SQLite with Popular ORM Frameworks

Last updated: December 08, 2024

Object-Relational Mapping (ORM) frameworks simplify database interactions by letting developers interact with databases using a higher level of abstraction. SQLite, being a lightweight, disk-based database, is widely used in small to medium-scale applications. In this article, we’ll explore how you can use SQLite with popular ORM frameworks such as SQLAlchemy, Django's ORM, and Entity Framework Core. Each framework provides a different yet seamless way to utilize SQLite for efficient data management.

Using SQLite with SQLAlchemy

SQLAlchemy is a Python SQL toolkit and ORM widely used for database handling. Here's how you can set up and use SQLite with SQLAlchemy:

from sqlalchemy import create_engine, Column, Integer, String
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker

# SQLite connection
engine = create_engine('sqlite:///example.db')
Base = declarative_base()

# Define a sample model
class User(Base):
    __tablename__ = 'users'

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

Base.metadata.create_all(engine)

# Creating a session
Session = sessionmaker(bind=engine)
session = Session()

# Adding a new user
new_user = User(name='John Doe')
session.add(new_user)
session.commit()

Above, we define a simple User model and perform basic operations like adding an entry to the users table. SQLAlchemy automatically handles the conversion between class objects and database records.

Using SQLite with Django ORM

Django, a popular Python web framework, has its own ORM that works seamlessly with SQLite. Here's the basic setup to get started:

# settings.py
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': BASE_DIR / 'db.sqlite3',
    }
}

Ensure the database configuration in settings.py is set to use SQLite. Next, define your models in the models.py file:

from django.db import models

class User(models.Model):
    name = models.CharField(max_length=100)

Don't forget to run python manage.py makemigrations followed by python manage.py migrate to create the SQLite database and the necessary tables.

Now you can add a user to your User model:

# in any Python script inside Django project
from yourapp.models import User

new_user = User(name='John Doe')
new_user.save()

Using SQLite with Entity Framework Core

Entity Framework Core is .NET's ORM system. To employ SQLite with EF Core, follow these steps:

using System;
using Microsoft.EntityFrameworkCore;
using System.Linq;

public class ApplicationContext : DbContext
{
    public DbSet<User> Users { get; set; }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        optionsBuilder.UseSqlite("Data Source=users.db");
    }
}

public class User
{
    public int Id { get; set; }
    public string Name { get; set; }
}

class Program
{
    static void Main()
    {
        using (var context = new ApplicationContext())
        {
            context.Database.EnsureCreated();

            var newUser = new User { Name = "John Doe" };
            context.Users.Add(newUser);
            context.SaveChanges();
        }
    }
}

This C# example shows you how to integrate SQLite in a .NET Core application to perform database operations. EF Core automatically maps the class properties to database columns, making it efficient to manage data without writing raw SQL queries.

Conclusion

SQLite's compatibility with multiple ORM frameworks allows it to be versatile across different programming ecosystems. Be it Python with SQLAlchemy or Django, or C# with Entity Framework Core, developers can take advantage of SQLite's simplicity and ORM's powerful abstractions for effective data management. It's a great choice for developing applications that require efficient and straightforward database solutions.

Next Article: How to Optimize Data Transfer Between SQLite and External Systems

Previous Article: Tips for Managing Data Formats During SQLite Migrations

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