Connecting Python with SQLite
Connecting Python with SQLite
Interacting with SQLite in Python requires understanding the relationship between the Connection, the Cursor, transactions, and parameter substitution. In this topic, we examine how to execute queries safely, access results as structured mappings, and defend against critical SQL injection attacks.
1. The Core Lifecycle: Connection & Cursor
A standard SQLite session follows four stages:
- 1Connect: Open a connection object to the database file.
- 2Cursor: Obtain a cursor to execute SQL commands and traverse result sets.
- 3Execute & Commit: Run SQL statements and commit data mutations.
- 4Close: Release locks and close resources.
2. The Context Manager Pattern: Automatic Commit & Rollback
Python's sqlite3.Connection can act as a context manager. When used in a with conn: block:
- If all statements finish without error, Python calls
conn.commit()automatically. - If an exception occurs, Python calls
conn.rollback()automatically, preserving data integrity.
3. The Number One Security Vulnerability: SQL Injection
% formatting, or + string concatenation to build SQL statements with user input!The Vulnerable Pattern:
The Secure Pythonic Solution: Parameterized Queries
Always pass parameters as a tuple using the ? placeholder (qmark style) or dictionary keys with :name:
The database engine compiles the query structure before inserting parameter values, making SQL injection impossible.
4. Traversing Queries: fetchone(), fetchall(), & fetchmany()
5. Modern Row Factory: Accessing Columns by Name
By default, SQLite queries return raw tuples (row[0], row[1]). Setting conn.row_factory = sqlite3.Row allows accessing columns by name like a dictionary while retaining indexability:
Multiple Choice Questions
1. Why should you NEVER use Python f-strings or string concatenation to build SQL queries with user input?
A. F-strings execute too slowly in loops B. It leaves the application vulnerable to critical SQL Injection attacks C. SQLite cannot parse curly braces D. Python limits SQL strings to 256 characters Answer: B Explanation: Concatenating raw user inputs into SQL strings allows attackers to manipulate SQL syntax and bypass security or steal data (SQL Injection).
2. What symbol is used as the standard parameter placeholder in Python's sqlite3 module?
A. %s B. ? C. $ D. @ Answer: B Explanation: Python's SQLite driver uses ? (qmark style) for positional parameterized queries.
3. What does setting conn.row_factory = sqlite3.Row accomplish?
A. It locks the database against read operations B. It allows query result rows to be accessed by column name (like a dictionary) in addition to numeric index C. It converts SQLite into MongoDB D. It automatically generates primary keys Answer: B Explanation: sqlite3.Row provides case-insensitive name-based column access along with tuple indexing.
4. What happens when a with connection: context manager block encounters an unhandled exception?
A. The script restarts automatically B. The transaction is automatically rolled back (rollback()), undoing partial changes C. The changes are permanently committed anyway D. The .db file is deleted Answer: B Explanation: Using with connection: automatically commits on successful completion and rolls back on unhandled exceptions.
5. What does cursor.fetchone() return if no more records remain in the query result set?
A. () (Empty tuple) B. None C. Raises StopIteration D. False Answer: B Explanation: cursor.fetchone() returns the next row as a tuple, or None when the result set is exhausted.
CRUD Operations
Continue learning with hands-on practice, examples, and exercises in the upcoming topic.
Related Lessons
| Previous Lesson | Next Lesson |
|---|---|
| SQLite Installation & Setup | CRUD Operations |
Practice Quiz
Test your understanding of this lesson with 5 questions. Each question has one correct answer.