Databases with SQLite · 3 / 15 Theory

Parameters, UPDATE and DELETE

So far you have read data. To change it, INSERT, UPDATE and DELETE are used. But first, the most important security rule when working with databases.

Never build SQL by gluing text

If you build the SQL command with an f-string and the text was typed by a user, that user can change the meaning of your query. This is SQL injection, one of the most common security flaws.

import sqlite3

con = sqlite3.connect(":memory:")
con.execute("CREATE TABLE users (name TEXT, password TEXT)")
con.executemany("INSERT INTO users VALUES (?, ?)", [("ana", "s3cr3t"), ("luis", "1234")])

entry = "x' OR '1'='1"   # what an attacker types

# BAD: the text is glued into the SQL
sql = f"SELECT name FROM users WHERE name = '{entry}'"
print(sql)   # SELECT name FROM users WHERE name = 'x' OR '1'='1'
print(con.execute(sql).fetchall())   # [('ana',), ('luis',)]   it returns everybody!

# GOOD: parameters
print(con.execute("SELECT name FROM users WHERE name = ?", (entry,)).fetchall())   # []

With parameters, the value is never interpreted as SQL: it is always treated as data. The ? placeholders are filled in order with a tuple (even a one-element one: (value,)). There are also named placeholders, :name, with a dictionary.

import sqlite3

con = sqlite3.connect(":memory:")
con.execute("CREATE TABLE users (name TEXT, age INTEGER)")
con.execute("INSERT INTO users VALUES (:name, :age)", {"name": "ana", "age": 30})
print(con.execute("SELECT * FROM users WHERE age > :minimum", {"minimum": 18}).fetchall())   # [('ana', 30)]

Parameters are for values, not for table or column names. Names must not come from the user without validating them first.

Searching with LIKE and parameters

The % wildcard is concatenated in the SQL with ||, and the text is passed as a parameter.

import sqlite3

con = sqlite3.connect(":memory:")
con.execute("CREATE TABLE users (name TEXT)")
con.executemany("INSERT INTO users VALUES (?)", [("Ana",), ("anabel",), ("Juan",)])

text = "an"
print(con.execute("SELECT name FROM users WHERE name LIKE '%' || ? || '%' ORDER BY name", (text,)).fetchall())
# [('Ana',), ('Juan',), ('anabel',)]

It is the technique of Safe search.

UPDATE: modifying rows

import sqlite3

con = sqlite3.connect(":memory:")
con.execute("CREATE TABLE inventory (item TEXT, quantity INTEGER)")
con.executemany("INSERT INTO inventory VALUES (?, ?)", [("screw", 10), ("nail", 5)])

cur = con.execute("UPDATE inventory SET quantity = quantity - ? WHERE item = ?", (3, "screw"))
print(cur.rowcount)   # 1   (modified rows)

cur = con.execute("UPDATE inventory SET quantity = 0 WHERE item = ?", ("file",))
print(cur.rowcount)   # 0   (there is no "file" item)

print(con.execute("SELECT * FROM inventory ORDER BY item").fetchall())   # [('nail', 5), ('screw', 7)]

SET states the columns that change, and they can use their own value (quantity - 3). Without WHERE, UPDATE changes all the rows. The cursor's rowcount attribute tells how many rows were affected, and it is the way to know whether the item existed.

DELETE: deleting rows

import sqlite3

con = sqlite3.connect(":memory:")
con.execute("CREATE TABLE inventory (item TEXT, quantity INTEGER)")
con.executemany("INSERT INTO inventory VALUES (?, ?)", [("screw", 10), ("nail", 0), ("saw", 1)])

cur = con.execute("DELETE FROM inventory WHERE quantity = 0")
print(cur.rowcount)   # 1
print(con.execute("SELECT item FROM inventory ORDER BY item").fetchall())   # [('saw',), ('screw',)]

Without WHERE, DELETE deletes all the rows. Always check the condition. You practise it with Update and delete.

Identifier of the inserted row

import sqlite3

con = sqlite3.connect(":memory:")
con.execute("CREATE TABLE tasks (id INTEGER PRIMARY KEY, text TEXT)")
cur = con.execute("INSERT INTO tasks (text) VALUES (?)", ("study",))
print(cur.lastrowid)   # 1
cur = con.execute("INSERT INTO tasks (text) VALUES (?)", ("rest",))
print(cur.lastrowid)   # 2

An INTEGER PRIMARY KEY column numbers itself (1, 2, 3...) and cursor.lastrowid gives the number of the last inserted row.