Home / Python / Day 9: Automation & Databases / Working with SQLite Databases

Working with SQLite Databases

SQLite is a lightweight, file-based database built into Python via the sqlite3 module — perfect for small applications and learning SQL.

What is SQLite?

SQLite is a serverless, file-based relational database. Python includes the sqlite3 module in its standard library, so no installation is needed. The entire database lives in a single .db file.

Connecting and Cursors

sqlite3.connect("file.db") opens (or creates) a database file and returns a connection object. A cursor is used to execute SQL statements.

Creating Tables

Use CREATE TABLE IF NOT EXISTS with standard SQL syntax to define your schema.

Inserting Data Safely

Always use parameterized queries (placeholders ?) instead of string formatting to prevent SQL injection and handle special characters correctly.

Querying Data

cursor.execute("SELECT ...") followed by fetchone(), fetchall(), or iterating over the cursor retrieves results.

Committing and Closing

Changes (INSERT, UPDATE, DELETE) must be saved with connection.commit(). Always close the connection when done, or use a with statement for automatic cleanup.