How to store, query, and manage data using SQLite in Python
SQLite is a lightweight, file‑based database engine included with Python. It requires no server setup and is perfect for small to medium‑sized applications, prototypes, and learning SQL.
Use Python’s built‑in sqlite3 module:
import sqlite3
connection = sqlite3.connect("example.db")
cursor = connection.cursor()
cursor.execute("""
CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT,
age INTEGER
)
""")
connection.commit()
cursor.execute("INSERT INTO users (name, age) VALUES (?, ?)", ("Alice", 30))
connection.commit()
cursor.execute("SELECT * FROM users")
rows = cursor.fetchall()
for row in rows:
print(row)
cursor.execute("UPDATE users SET age = ? WHERE name = ?", (31, "Alice"))
connection.commit()
cursor.execute("DELETE FROM users WHERE name = ?", ("Alice",))
connection.commit()
You can simplify database handling using with:
with sqlite3.connect("example.db") as conn:
cursor = conn.cursor()
cursor.execute("SELECT * FROM users")
print(cursor.fetchall())
Now that you can work with SQLite databases, you're ready to explore how to build graphical applications in Lesson 19: Introduction to GUI Programming (Tkinter).
← Back to Lesson Index