- Phase: 9. Databases & Web Apps
- Duration: 2 hours
- Connect to an SQLite database using the sqlite3 module
- Create tables and perform CRUD operations (INSERT, SELECT, UPDATE, DELETE)
- Use parameterized queries to prevent SQL injection
- Commit transactions and close connections properly
- SQLite overview
- sqlite3 module
- Connecting to a database with .connect
- Creating tables with CREATE TABLE
- Inserting data with INSERT
- Querying with SELECT
- Updating with UPDATE
- Deleting with DELETE
- Parameterized queries with ?
- Committing and closing connections
Modules 000-081.
import sqlite3
conn = sqlite3.connect('example.db')
cursor = conn.cursor()
cursor.execute('''CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
age INTEGER
)''')
cursor.execute('INSERT INTO users (name, age) VALUES (?, ?)', ('Alice', 30))
conn.commit()
cursor.execute('SELECT * FROM users WHERE age > ?', (25,))
rows = cursor.fetchall()
print(rows)
conn.close()- Python sqlite3 documentation
- SQLite official site: https://sqlite.org
- DB Browser for SQLite (GUI tool)