DB API
The Python Database API (DB-API) is a standard specification (PEP 249) that defines a consistent interface for how Python libraries should connect to databases and execute queries - so that code written for one database driver looks and behaves similarly to code written for another.
Core DB-API Objects
- Connection object - represents the connection to the database
- Cursor object - used to execute SQL statements and fetch results
Common DB-API Methods
- connect() - opens a connection to the database
- cursor() - creates a cursor object from a connection
- execute() - runs a SQL statement
- fetchone() / fetchall() - retrieve one row or all rows from the last executed query
- commit() - saves changes made by INSERT, UPDATE, or DELETE statements
- close() - closes the cursor or connection
Example Using sqlite3
import sqlite3
conn = sqlite3.connect("uncodemy.db")
cursor = conn.cursor()
cursor.execute("SELECT first_name FROM customers")
rows = cursor.fetchall()
for row in rows:
print(row)
conn.close()
Because most Python database libraries follow the same DB-API pattern, learning it once with sqlite3 makes it much easier to switch to psycopg2 or PyMySQL later.