Database How Programs Talk to Databases
What you will learn
- The usual steps: connect, execute, fetch, commit, close
- What a cursor and a result are
- Why to pass values as parameters, never glue them into SQL text
- That other languages follow the same pattern
1. The usual steps
Whatever the language or DBMS, a program normally does this:
| Step | Python sqlite3 |
|---|---|
| Connect | con = sqlite3.connect(...) |
| Send a statement | con.execute("SQL ...") |
| Read the rows | .fetchall(), .fetchone() or a for loop |
| Save changes | con.commit() |
| Close | con.close() |
import sqlite3
con = sqlite3.connect(":memory:")
con.execute("CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT)")
con.execute("INSERT INTO users (name) VALUES (?)", ("Rina",))
cur = con.execute("SELECT id, name FROM users")
print(cur.fetchall())
print([d[0] for d in cur.description])
[(1, 'Rina')]
['id', 'name']
executereturns a cursor, an object you read the results from.- Each row comes back as a tuple.
cur.descriptionholds the column names. :memory:is a database that exists only while the program runs, handy for experiments.
2. Parameters: never glue values into SQL
The ? in the insert is a placeholder. The value goes in separately, so the DBMS treats it only as data. Compare with building the SQL text from user input:
name = "x' OR '1'='1"
unsafe = f"SELECT * FROM users WHERE name = '{name}'"
print(unsafe)
print(con.execute(unsafe).fetchall())
print(con.execute("SELECT * FROM users WHERE name = ?", (name,)).fetchall())
SELECT * FROM users WHERE name = 'x' OR '1'='1'
[(1, 'Rina')]
[]
- The first query is not what the programmer meant. The visitor's text closed the quote and added
OR '1'='1', which is always true, so it returned every user. - The second query treated the whole text as a name, found no such user, and returned nothing.
Gluing text into SQL is called an SQL injection weakness. Lesson 8.5 covers it in depth; for now, remember: always use placeholders.
3. Saving changes
Changes made by INSERT, UPDATE and DELETE happen inside a transaction and are not permanent until you commit (chapter 6). Python lets you use the connection as a block that commits when it ends normally:
with con:
con.execute("INSERT INTO users (name) VALUES ('Sam')")
print(con.execute("SELECT COUNT(*) FROM users").fetchone())
(2,)
(If an error occurs inside the block, the changes are rolled back instead.)
4. Names for columns
Tuples are positional. To use column names, ask for rows that support them:
con.row_factory = sqlite3.Row
r = con.execute("SELECT id, name FROM users").fetchone()
print(r["name"], tuple(r), r.keys())
Rina (1, 'Rina') ['id', 'name']
5. Other languages
Java, PHP, JavaScript, C# and others use the same pattern with different names: open a connection, run a statement with parameters, read rows, commit, close. Web frameworks (such as Django) add a layer on top called an ORM that writes the SQL for you; understanding the SQL underneath still helps.
Worked example: a safe lookup function
def find_user(con, name):
rows = con.execute("SELECT id, name FROM users WHERE name = ?", (name,)).fetchall()
return [tuple(r) for r in rows] # plain tuples, even with row_factory set
print(find_user(con, "Sam"))
print(find_user(con, "x' OR '1'='1"))
[(2, 'Sam')]
[]
The function finds Sam, and a hostile text finds nothing instead of every user. Names are made up.
Common mistakes
- Building SQL with f-strings or
+from user input. - Forgetting to commit, then wondering where the data went.
- Not closing connections in long-running programs.
- Passing a single value without a tuple:
(name,)needs the comma.
Key takeaways
- Programs connect, send SQL, fetch rows, commit and close.
- Rows come back through a cursor, as tuples or named rows.
- Use
?placeholders; never glue values into SQL. - Other languages follow the same steps.
Practice
1. List the five usual steps.
Show answer
Connect, execute a statement, fetch rows, commit, close.
2. What is a placeholder?
Show answer
A ? in the SQL where a separately supplied value goes, so it is treated purely as data.
3. Why did the unsafe query return all users?
Show answer
The input closed the quote and added OR '1'='1', which is always true.
4. Why is (name,) written with a comma?
Show answer
A one-item tuple needs the comma; otherwise it is just name in brackets.
5. What does with con: do?
Show answer
It commits at the end of the block if all went well, and rolls back if an error occurs.
6. What does cur.description give you?
Show answer
Information about the result columns, whose first item for each column is its name.