🐍 Lesson 34: Flask Databases – SQLite & SQLAlchemy Basics

Welcome to Lesson 34! Today we’ll learn how to store and manage data in your Flask apps using SQLite and SQLAlchemy. Databases are essential for dynamic websites, login systems, to-do apps, and dashboards.


💡 Key Benefits of Learning Databases with Flask

  • Learn how to store and retrieve data in your web apps
  • Implement user authentication systems with ease
  • Manage large datasets effectively
  • Handle dynamic content in websites and web apps
  • Understand the power of SQLAlchemy for database operations

🌐 Why Use a Database?

  • Store user information securely
  • Save application data (posts, tasks, products)
  • Retrieve and update data easily
  • Work with dynamic web apps

📦 1. Installing SQLAlchemy


pip install flask_sqlalchemy

📂 2. Project Structure


project/
│── app.py
│── templates/
    │── home.html

📦 3. Setting Up SQLite with Flask


from flask import Flask
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///data.db'
db = SQLAlchemy(app)

📦 4. Creating a Database Model


class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(50), nullable=False)
    email = db.Column(db.String(50), unique=True, nullable=False)

    def __repr__(self):
        return f""

📦 5. Creating the Database


with app.app_context():
    db.create_all()

📦 6. Adding & Querying Records


# Adding a user
with app.app_context():
    new_user = User(name="Alice", email="alice@example.com")
    db.session.add(new_user)
    db.session.commit()

# Querying users
users = User.query.all()
for user in users:
    print(user.name, user.email)

📦 7. Updating & Deleting Records


with app.app_context():
    user = User.query.first()
    user.name = "Alice Updated"
    db.session.commit()

    # Delete user
    db.session.delete(user)
    db.session.commit()

📌 8. Why SQLAlchemy Is Powerful

  • Object-oriented approach to databases
  • Automatically maps Python classes to tables
  • Supports SQLite, MySQL, PostgreSQL, and more
  • Makes database operations clean and easy

❓ Frequently Asked Questions (FAQ)

1. What is SQLAlchemy?

SQLAlchemy is a powerful Object-Relational Mapping (ORM) library that simplifies database interactions in Python. It provides a Pythonic way to interact with databases, making it easier to manage data in your Flask app.

2. Can I use SQLAlchemy with databases other than SQLite?

Yes! SQLAlchemy supports multiple database systems, including MySQL, PostgreSQL, and others. You can easily switch between them by changing the URI in your app’s configuration.

3. How does Flask-SQLAlchemy differ from regular SQLAlchemy?

Flask-SQLAlchemy is an extension for Flask that simplifies the integration of SQLAlchemy into Flask apps, making it easier to use SQLAlchemy with Flask-specific features like app context and request handling.

4. How do I create relationships between models in SQLAlchemy?

You can use SQLAlchemy’s relationship function to link models. For example, if you have a Post model with a foreign key to the User model, you can define a relationship to query related data more easily.

5. Can I perform raw SQL queries with SQLAlchemy?

Yes, SQLAlchemy allows you to perform raw SQL queries if needed. While the ORM is powerful, raw queries can be useful for complex queries or optimization.

❌ Common Misconceptions About SQLAlchemy

  • “SQLAlchemy is only for advanced users.” – SQLAlchemy is beginner-friendly, especially with Flask-SQLAlchemy, which simplifies database management.
  • “SQLAlchemy is slow for large projects.” – With proper indexing and optimization, SQLAlchemy performs well for large projects.
  • “You need to know SQL to use SQLAlchemy.” – While knowing SQL is helpful, SQLAlchemy allows you to interact with databases using Python objects without writing SQL directly.

🧪 Practice

  1. Create a Product table with name, price, and quantity.
  2. Add 3 products to the database and print them.
  3. Update the price of a product and delete another product.
  4. Build a simple HTML page to display all users from the database.

➡ Next Lesson

Go to Lesson 35 →

Comments

Popular posts from this blog

How to Install Geany 2.1 on Windows 10/11 (2026) | Step-by-Step Guide

How to Uninstall Bluefish 2.2.19 on Windows 10/11 (2026) | Step-by-Step Guide

How to Install Visual Studio 2026 on Windows 10/11 | Step-by-Step Guide