Running SQL from Python: execute, fetchall and commit
Runs an SQL statement from Python. Then fetchall() returns the result rows as tuples, and conn.commit() saves INSERT or UPDATE changes. Use ? placeholders for values.
Understanding Running SQL from Python: execute, fetchall and commit in QCE Digital Solutions Unit 4
What it does: The ? marks where the value goes and the tuple (house,) supplies it. This is safer than building the SQL string by hand. fetchone() gives one tuple (or None if there are no rows), while fetchall() gives a list of all the rows. execute() sends the SQL to the database. fetchall() takes no SQL and only returns rows from a query you already ran. INSERT, UPDATE and DELETE changes are only saved once you call conn.commit() on the connection. fetchall() is for reading SELECT results. The ? placeholder is filled by a tuple passed as the second argument. This keeps user input out of the SQL text and avoids SQL injection.
Common mistakes: fetchall is a method, so it needs brackets to run. Without them rows just holds the method itself, not the result rows. It should be rows = cur.fetchall(). commit() belongs to the connection object, not the cursor. The line should be conn.commit() so the UPDATE is saved.
Free printable worksheet with full answer key — or add this module to a class and your students practise it interactively.
This module's key terms are also in a printable crossword (Modules 334–401) and word search (Modules 127–401).
Take this worksheet further — free with Cloodit
Each concept is reinforced from every angle — learned, then applied, then tested.
Cloodit turns curriculum-aligned coding content into journeys students work through one biome at a time.
Over 100 of them, across seven natural biomes.
Turns their work into revision material ready for Flash Cards and Exam study.
Live, competitive practice for the start of the lesson or a teacher-led lesson finisher.
Honour your top performers, or encourage a student who's trying hard — ready to print in seconds.
Quick Questions
Match the Pairs
Key Term
cursor.execute()Fill in the Blanks
Spot the Error
Student with a class code? Join your class →