
Working with Databases: SQLite and SQLAlchemy
π Introduction
Databases are the foundation of almost all applications, including automation and analytics tools, mobile apps, and web apps. Two strong technologies in the Python world facilitate database interaction for developers:
- SQLite is a file-based database engine that is lightweight.
- An advanced Python SQL toolkit and object relational mapper (ORM) is called SQLAlchemy.
π§© What is SQLite?
SQLite is a serverless, self-contained SQL database engine that requires no setup. It is perfect for local development environments or small to medium-sized applications.
β Why Use SQLite?
- Data is stored in a single.db file, therefore no server is required.
- includes Python (Sqlite3) built in.
- Excellent for rapid testing or prototypes
π Getting Started with SQLite in Python
The sqlite3 module is pre-installed in Python. To utilize it, follow these steps:
1. Create a Database and Connect
import sqlite3
conn = sqlite3.connect('my_database.db') # Creates or connects to DB
cursor = conn.cursor()
2. Create a Table
cursor.execute('''
CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
email TEXT UNIQUE NOT NULL
)
''')
conn.commit()
3. Insert Data
cursor.execute('''
INSERT INTO users (name, email)
VALUES (?, ?)
''', ("Alice", "alice@example.com"))
conn.commit()
4. Query Data
cursor.execute("SELECT * FROM users")
rows = cursor.fetchall()
for row in rows:
print(row)
5. Close Connection
conn.close()
β
Quick Tip: Always use parameterized queries (?
) to prevent SQL injection.
βοΈ Enter SQLAlchemy β ORM Made Easy
Although SQLite3 is excellent, SQLAlchemy goes above and beyond by providing an Object Relational Mapping (ORM) method and abstracting SQL syntax.
π§ What is SQLAlchemy?
Instead of utilizing raw SQL queries, SQLAlchemy allows you to work with databases using Python classes and objects. With a common syntax, it supports a variety of databases, including PostgreSQL, MySQL, SQLite, and others.
π§ Installing SQLAlchemy
pip install SQLAlchemy
π Getting Started with SQLAlchemy (Using SQLite)
1. Setup Engine and Base
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
engine = create_engine('sqlite:///my_database.db', echo=True)
Base = declarative_base()
Session = sessionmaker(bind=engine)
session = Session()
2. Define Models (Tables)
from sqlalchemy import Column, Integer, String
class User(Base):
__tablename__ = 'users'
id = Column(Integer, primary_key=True)
name = Column(String)
email = Column(String, unique=True)
3. Create Tables
Base.metadata.create_all(engine)
4. Insert Records
new_user = User(name="Bob", email="bob@example.com")
session.add(new_user)
session.commit()
5. Query Records
users = session.query(User).all()
for user in users:
print(user.id, user.name, user.email)
π SQLite vs SQLAlchemy β Which One to Use?
Feature | sqlite3 (Raw SQL) | SQLAlchemy (ORM) |
---|---|---|
Learning Curve | Simple | Moderate |
SQL Required? | Yes | Minimal |
Abstraction | None | High |
Code Readability | Lower | Cleaner |
Portability | Good | Excellent |
Recommended for | Quick tests, beginners | Scalable apps, larger projects |
π Real-World Use Case Example
Imagine you’re building a user registration app:
- With sqlite3, you’d manually write SQL queries for every operation.
- With SQLAlchemy, you define your schema once and perform CRUD using Python objects. It improves readability, security, and maintainability.
π§ͺ Bonus: Combining SQLite + SQLAlchemy in a Flask App
# In Flask, using SQLAlchemy with SQLite
from flask_sqlalchemy import SQLAlchemy
from flask import Flask
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///site.db'
db = SQLAlchemy(app)
This simple setup enables full-stack development with Python, Flask, SQLite, and SQLAlchemy.
π― Final Thoughts
If you’re starting out or working on a small project, SQLite is perfect. But as your application grows, SQLAlchemy becomes a must-have tool to manage your database cleanly and efficiently.
You can also read for :-
What is Web Technology? A Complete Guide for Beginners in 2025
What is DBMS? A Beginnerβs Guide to Database Management Systems in 2025
Introduction to Serverless Databases: Firebase, AWS DynamoDB, & More
Leave a Reply