Skip to main content
Flask Basics Tutorial
CHAPTER 08 Beginner

Working with Databases in Flask

Updated: May 14, 2026
25 min read

# CHAPTER 8

Working with Databases in Flask

1. Introduction

A web application without a database is just a static brochure; it forgets everything the moment the server restarts. To build a blog, an e-commerce site, or a social network, you must persist data. In this chapter, we will discuss the database landscape within the Python ecosystem. Because Flask is a microframework, it does not include a built-in database engine. We will explore how to connect Flask to SQLite and MySQL, and introduce the concept of an Object-Relational Mapper (ORM).

2. Learning Objectives

By the end of this chapter, you will be able to:
  • Understand how databases integrate with Flask.
  • Differentiate between raw SQL queries and an ORM.
  • Identify the role of SQLite for development.
  • Configure a basic raw database connection in Python.

3. Beginner-Friendly Explanation

Imagine a Library.
  • The Application (Flask): The Librarian at the front desk.
  • The Database: The massive warehouse in the back containing thousands of books (Data).
To get a book, the Librarian cannot walk into the warehouse blindly. They must follow a strict set of instructions (SQL) to find the exact aisle and shelf. However, learning the complex SQL language is difficult. Instead, we hire an Assistant (The ORM). The Librarian simply tells the Assistant in plain English (Python), "Get me all books by Stephen King." The Assistant translates this into complex warehouse instructions (SQL), retrieves the books, and hands them to the Librarian.

4. The Database Choice

Because Flask is "micro," it forces you to choose your database and your integration method. You have two main paths:
  1. 1. Raw SQL: You write raw SQL strings (e.g., SELECT * FROM users) inside your Python code. Fast, but dangerous (SQL Injection) and hard to maintain.
  1. 2. An ORM (Object-Relational Mapper): You define Python Classes, and a third-party library automatically translates your Python code into perfect SQL. This is the industry standard.

The undisputed king of Python ORMs is SQLAlchemy. We will use the Flask-SQLAlchemy extension to bind it to our application.

5. Development vs. Production Databases

Before writing code, you must understand where the data lives.
  • SQLite (Development): A lightweight database that stores everything inside a single file (e.g., app.db) on your hard drive. It requires zero installation. It is perfect for learning and building prototypes on your laptop.
  • MySQL / PostgreSQL (Production): Heavy-duty database servers that run independently. They handle thousands of simultaneous connections. When you deploy your app to the internet, you MUST switch to one of these.

*The beauty of an ORM like SQLAlchemy is that you can develop using SQLite, and switch to MySQL later by changing exactly ONE line of code. The ORM handles the SQL translation differences automatically!*

6. Step 1: Installing the Extension

To bridge Flask and SQLAlchemy, we install the official extension. Open your terminal (with the virtual environment active):
bash
1
pip install Flask-SQLAlchemy

7. Step 2: Configuring the Connection

We must tell Flask where the database is located. We do this using a connection string (URI).

In app.py:

python
12345678910111213141516171819202122232425
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
import os

# Get the absolute path of the directory containing app.py
basedir = os.path.abspath(os.path.dirname(__file__))

app = Flask(__name__)

# Configure the SQLite database location
# This creates a file named 'app.db' in the same folder as app.py
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + os.path.join(basedir, 'app.db')

# Disable a feature that takes up unnecessary memory
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False

# Initialize the Database Assistant (SQLAlchemy) and bind it to our App
db = SQLAlchemy(app)

@app.route('/')
def home():
    return "Database Configured!"

if __name__ == '__main__':
    app.run(debug=True)

8. Backend Workflow: Connection Strings (URIs)

The line app.config['SQLALCHEMYDATABASEURI'] is the most important line in database management. It tells the ORM exactly what dialect to speak and where to connect.
  • SQLite Example: 'sqlite:///app.db' (Talks to a local file).
  • MySQL Example: 'mysql+pymysql://username:password@localhost/dbname'
  • PostgreSQL Example: 'postgresql://username:password@localhost/dbname'

When you are ready to launch your startup, you simply change this string from SQLite to your live cloud MySQL server, and the application continues working identically.

9. Best Practices

  • Security: Notice the MySQL connection string contains a password. NEVER type your live database password directly into app.py and upload it to GitHub. You must use Environment Variables (which we will cover in Chapter 19) to inject the connection string securely from a hidden file.

10. Common Mistakes

  • ModuleNotFoundError: If you run the code and Python crashes complaining about flasksqlalchemy, it means you forgot to install it, OR you installed it globally instead of inside your active (venv). Always ensure your virtual environment is activated before running pip install.

11. Exercises

  1. 1. Explain the architectural advantage of using an ORM (Object-Relational Mapper) like SQLAlchemy over writing raw SQL strings directly in your Python routes.

12. Coding Challenges

  • Challenge: Look up the documentation for Flask-SQLAlchemy. How would you configure the application to use an in-memory SQLite database (a database that exists purely in RAM and deletes itself when the server stops, often used for automated testing)? (Hint: The URI is 'sqlite:///:memory:').

13. MCQs with Answers

Question 1

What is the primary advantage of using the SQLite database during the development phase of a Flask application?

Question 2

Which third-party extension is considered the industry standard for bridging a Flask application to the SQLAlchemy ORM?

14. Interview Questions

  • Q: Explain the concept of Database Abstraction provided by an ORM. How does it allow a developer to transition an application from SQLite to PostgreSQL with minimal code changes?
  • Q: If you were tasked with building a high-traffic e-commerce platform in Flask, why would you strictly avoid using SQLite in the production environment?

15. FAQs

Q: Do I need to know SQL to use Flask? A: Knowing the basics of SQL (Tables, Rows, Columns, Foreign Keys) is highly recommended so you understand what the ORM is doing under the hood. However, you will rarely need to write actual SQL syntax when using SQLAlchemy.

16. Summary

In Chapter 8, we prepared our application to persist data permanently. We learned that Flask's micro-nature requires us to choose our own database tools, leading us to adopt Flask-SQLAlchemy as our ORM. We explored the differences between development databases (SQLite) and production databases (MySQL/PostgreSQL), and successfully configured our app.py with the critical SQLALCHEMY
DATABASE_URI connection string.

17. Next Chapter Recommendation

Our database connection is established, but we don't have any tables or data. Proceed to Chapter 9: Flask SQLAlchemy ORM Basics.

Finish this Chapter

Save your progress on your learning path and prepare for coding interview challenges.

Discussion

Join the discussion

Log in or create a free account to participate.

Sort: ·