Edexcel International Advanced Level Computer Science, point 8.3.2
Manipulating data means adding, changing and removing the rows in tables. In SQL these are INSERT, UPDATE and DELETE. Python runs them through the sqlite3 module. (Check the PLS for the exact methods allowed.)
The examples use this setup:
import sqlite3
conn = sqlite3.connect(":memory:")
cur = conn.cursor()
cur.execute("""CREATE TABLE Player (
PlayerID INTEGER PRIMARY KEY,
Name TEXT NOT NULL,
Team TEXT,
Goals INTEGER DEFAULT 0)""")
Parameterised queries
Never build SQL by joining strings with user input. Use ? placeholders and pass the values separately.
name = input("Name: ")
# Unsafe: cur.execute("INSERT ... VALUES ('" + name + "')")
cur.execute("INSERT INTO Player (Name, Team, Goals) VALUES (?, ?, ?)",
(name, "Reds", 0))
- The values are given as a tuple (note the comma in a one-item tuple:
(name,)). - The database treats the values as data, never as SQL.
SQL injection
If user input is pasted into the SQL text, an attacker can enter SQL code instead of a name. For example, typing x'; DROP TABLE Player; -- could delete the table. Placeholders prevent this. They also handle quotes in names correctly (such as O'Neil).
a. Insert
cur.execute("INSERT INTO Player (Name, Team, Goals) VALUES (?, ?, ?)",
("Mia Chen", "Reds", 4))
print(cur.lastrowid) # the ID given to the row just inserted
rows = [("Leo Grant", "Blues", 7), ("Ava Moss", "Reds", 2)]
sql = "INSERT INTO Player (Name, Team, Goals) VALUES (?, ?, ?)"
cur.executemany(sql, rows)
conn.commit() # save
lastrowidgives the ID of the row added by the lastexecute(). It isn't updated byexecutemany(), so read it straight after a single insert.executemanyinserts many rows with one statement.- A primary key set to
INTEGER PRIMARY KEYis given automatically if you leave it out. - A duplicate primary key, or a missing
NOT NULLvalue, raisessqlite3.IntegrityError.
b. Update
cur.execute("UPDATE Player SET Team = ? WHERE Name = ?",
("Blues", "Mia Chen"))
cur.execute("UPDATE Player SET Goals = Goals + 1 WHERE Team = ?",
("Reds",))
conn.commit()
print(cur.rowcount) # how many rows were changed
- Always include
WHERE, otherwise every row is changed. SETcan calculate from the current value (Goals + 1).rowcountshows how many rows were affected (0 means nothing matched).
c. Delete
cur.execute("DELETE FROM Player WHERE PlayerID = ?", (3,))
conn.commit()
- Always include
WHERE:DELETE FROM Playerwith no condition deletes every row. - With foreign keys on (8.3.1), you can't delete a row that other rows refer to, unless those rows are deleted or changed first.
Transactions: commit and rollback
A transaction is a group of changes that must all succeed or all fail. The changes only become permanent when you commit().
try:
cur.execute(
"UPDATE Account SET Balance = Balance - 50 WHERE ID = 1")
cur.execute(
"UPDATE Account SET Balance = Balance + 50 WHERE ID = 2")
conn.commit() # both changes saved together
except sqlite3.Error:
conn.rollback() # undo both if anything went wrong
This stops money being taken from one account but never added to the other.
Worked example
Task: for a sports club, write a function that adds a player, one that adds goals to a player's total, and one that moves a player to another team, all safe from SQL injection, and test them.
def add_player(conn, name, team):
sql = "INSERT INTO Player (Name, Team) VALUES (?, ?)"
conn.execute(sql, (name, team))
conn.commit()
def add_goals(conn, player_id, goals):
sql = "UPDATE Player SET Goals = Goals + ? WHERE PlayerID = ?"
cur = conn.execute(sql, (goals, player_id))
conn.commit()
return cur.rowcount > 0 # True if a player was found
def move_team(conn, player_id, new_team):
cur = conn.execute("UPDATE Player SET Team = ? WHERE PlayerID = ?",
(new_team, player_id))
conn.commit()
return cur.rowcount > 0
# the apostrophe is handled safely
add_player(conn, "O'Neil", "Greens")
print(add_goals(conn, 1, 2)) # True
print(move_team(conn, 99, "Reds")) # False (no such player)
?placeholders make the functions safe from injection and handleO'Neilcorrectly.add_goalsadds to the current total (Goals = Goals + ?) instead of replacing it.rowcounttells the caller whether anything changed.- Each function commits after changing the data.
Exam tip: use ? placeholders, and be ready to explain why (SQL injection). Always use WHERE with UPDATE and DELETE. Remember to commit(), and to use rollback() when something fails in a group of changes. A one-value tuple needs a trailing comma.
Check yourself
What is SQL injection, and how is it prevented?
An attack in which SQL code is entered as input and run by the database. It is prevented by using parameterised queries with placeholders, so input is treated as data only.
What happens if you run UPDATE Player SET Goals = 0 with no WHERE clause?
Every row in the table is changed, so every player's goals become 0.
What does conn.rollback() do?
It undoes the changes made since the last commit.
Which method inserts many rows with one statement?
executemany().
What error occurs if you insert a duplicate primary key?
sqlite3.IntegrityError.