Python and the SQL Standard
Python interacts with relational databases through a standard specification called DB-API 2.0 (PEP 249). This ensures that whether you are using SQLite, MySQL, or PostgreSQL, the basic methods like connect(), execute(), and fetchone() remain consistent across different database drivers.
- Working with SQLite (Built-in)
Python comes with the sqlite3 module out of the box. It is perfect for local storage, mobile app testing, or small-scale automation tools. Since it's a file-based database, no server installation is required.
The Database Connection Workflow
Every SQL interaction in Python follows a specific hierarchy of objects: the Connection manages the link to the database, while the Cursor acts as a pointer to execute commands and fetch results.
- Parameterized Queries vs. Injection
As a Technical Lead, security is a priority. SQL Injection occurs when user input is directly concatenated into a query string. Python drivers prevent this by using placeholders (? for SQLite, %s for others).
Common DB-API Methods
| Method | Purpose | Returns |
|---|---|---|
| execute() | Runs a single SQL command | Cursor object |
| executemany() | Runs a command against a list of data | None |
| fetchone() | Retrieves the next row of a query result | Tuple or None |
| fetchall() | Retrieves all remaining rows | List of Tuples |
| commit() | Saves all current changes to the DB | None |
| rollback() | Undoes changes since the last commit | None |