๐Ÿ—„๏ธsqlite3: connect, execute, fetchall, context managerLESSON

SQLite3 in Python

Python's sqlite3 module provides a zero-dependency, serverless relational database. SQLite stores data in a single file (or entirely in memory), making it perfect for desktop apps, prototyping, testing, and small-to-medium scale data storage.

Connecting and Creating Tables

Cursor โ€” Executing SQL

The cursor is the object through which you execute SQL and fetch results:

Parameterized Queries โ€” Never Use String Formatting

Always use ? placeholders, never string formatting. String formatting leads to SQL injection:

Fetching Results

Connection as Context Manager

Using with conn: automatically commits on success and rolls back on exception:

Row Factory โ€” Named Column Access

By default, rows are tuples. Set row_factory = sqlite3.Row to access columns by name:

UPDATE and DELETE

Getting the Last Inserted ID

executemany โ€” Bulk Operations

Transactions

SQLite is transactional. In Python's sqlite3 module, INSERT/UPDATE/DELETE are automatically wrapped in a transaction unless you use isolation_level=None (autocommit mode):

Quick Reference

Knowledge Check

Why should you always use `?` placeholders in SQLite queries instead of Python string formatting?

What does `conn.row_factory = sqlite3.Row` do?

What happens when you use a connection as a context manager with `with conn:`?