Lazo Lab Sign up

App 7: Your First Website with Flask / Build a guestbook website

Lesson 7 of 10

A real database with SQLite

Messages in a list vanish when the server restarts. SQLite stores them in a file. Always use ? placeholders so input can never change your SQL.

Key points

  • sqlite3 is built into Python
  • CREATE TABLE IF NOT EXISTS
  • ? placeholders prevent SQL injection
import sqlite3

def db():
    conn = sqlite3.connect("guestbook.db")
    conn.execute("CREATE TABLE IF NOT EXISTS messages (id INTEGER PRIMARY KEY, body TEXT)")
    return conn

with db() as conn:
    conn.execute("INSERT INTO messages (body) VALUES (?)", (msg,))

Your turn

Store guestbook messages in SQLite so they survive restarts.

Watch a video on thisOpens YouTube search results for “A real database with SQLite” in a new tab

Quiz · +10 XP

What protects your queries from SQL injection?

Log in to save progress and earn XP.