Lesson 48 of 55
PythonDatabase Access with SQLite
20 minutes
Course progress87%
What you'll learn
Keep these ideas in mind as you work through the lesson.
Lesson 48 of 55
Python20 minutes
Keep these ideas in mind as you work through the lesson.
SQLite is a self‑contained, serverless SQL database that ships with Python—perfect for small to medium applications.
import sqlite3
# Connect (creates file if it doesn't exist)
conn = sqlite3.connect('example.db')
cur = conn.cursor()
# Create a table
cur.execute('CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY, name TEXT)')
# Insert a row
cur.execute('INSERT INTO users (name) VALUES (?)', ('Alice',))
conn.commit()
# Query all rows
cur.execute('SELECT * FROM users')
print('Rows:', cur.fetchall())
conn.close()
For larger projects you might prefer an ORM like SQLAlchemy to avoid raw SQL.