Lesson

SQL from Python: Queries, Parameters and Saving Changes

Send SQL queries to a SQLite database from a Python program with the sqlite3 module: connect, execute, fetch rows, pass values safely with parameters, and save or cancel changes.

Last updated:


How does a Python program ask a database a question and get the rows back?

In the SQL guide you typed queries into DB Browser and read the answer on the screen.
A program does the same in four steps: it connects to the database, creates a cursor that sends statements, executes a query, and fetches the rows into Python values.
The rows arrive as the tuples and lists of values and collections, so everything you learned there is now used on real query results.

This lesson uses sqlite3, the module that comes with Python for SQLite databases.
Here the SQL stays as text inside the program. An ORM (object-relational mapper, see the ORM lesson) writes such queries for you, so you work with Python objects instead of SQL strings.

The examples run in your browser: select Run from top to bottom, because the boxes of the page share their variables.
If you press Stop or reload, run the page again from the top.

A practice database in memory

A SQLite database is usually a file, such as the sql-practice.sqlite of the SQL guide.
In this page we create a small database in memory: the name ':memory:' asks SQLite for a temporary database that exists only while the connection stays open (a new connection to ':memory:' is a new, empty database).
It has a reduced version of the guide’s table daily_ridership:
five of its columns, filled with six days of the real data (three winter days and three summer days).

The function sqlite3.connect opens the database whose name you give it and returns a connection:
an object that represents the open database. The statements that build our table are long, so we write them as text between triple quotes:
text in triple quotes can continue over many lines. The method executescript runs several SQL statements that are separated by semicolons.
The first statement, CREATE TABLE, creates an empty table with named columns and a type for each; the second, INSERT INTO, adds the rows.
PRIMARY KEY marks the column whose value identifies each row, so no two rows can share a record_id.
In INSERT INTO table VALUES, with no list of column names, every row must give one value for every column, in the order of the table (the guide’s section on joining tables shows an INSERT as well).

import sqlite3

conn = sqlite3.connect(':memory:')
conn.executescript("""
CREATE TABLE daily_ridership (
    record_id INTEGER PRIMARY KEY,
    observation_date TEXT,
    season TEXT,
    working_day INTEGER,
    total_rides INTEGER
);
INSERT INTO daily_ridership VALUES
    (1, '2011-01-01', 'Winter', 0, 985),
    (2, '2011-01-02', 'Winter', 0, 801),
    (3, '2011-01-03', 'Winter', 1, 1349),
    (185, '2011-07-04', 'Summer', 0, 6043),
    (186, '2011-07-05', 'Summer', 1, 4665),
    (187, '2011-07-06', 'Summer', 1, 4629);
""")
print(type(conn))
<class 'sqlite3.Connection'>

The variable conn now refers to that connection (the word class in the output names its kind of object, as in objects and generator expressions).
On your own computer, sqlite3.connect('sql-practice.sqlite') would open the file of the SQL guide in the same way, and queries that name their columns, such as most of this page, would work there too.
That file has 731 rows and 16 columns, so the INSERT statements and the unpacking of five values into names on this page are written for our small table and would need changes.

Connect, execute, fetch

A cursor is an object that sends SQL to the database and holds the answer until you take it.
You create it from the connection. The method execute sends one statement.
The method fetchall takes all the rows of the answer as a list of tuples:

c = conn.cursor()
c.execute(
    """
        SELECT observation_date, total_rides
        FROM daily_ridership
        WHERE season = 'Summer'
    """
)
rows = c.fetchall()
print(rows)
print(rows[0][1])
[('2011-07-04', 6043), ('2011-07-05', 4665), ('2011-07-06', 4629)]
6043

The answer is a list of tuples: exactly the shape of values and collections.
The SQL is an ordinary Python text, in double quotes here so that the single quotes of 'Summer' can stay inside it.

There are three ways to take the rows, and a cursor remembers where it stopped:

  • The method fetchone takes the next row as a tuple, and returns None when no row is left.
  • The method fetchmany takes the next rows as a list; fetchmany(2) takes two.
  • A for loop over the cursor takes the rest, one row at a time, and the loop header can unpack the values of each tuple, as in loops and functions.
c.execute("SELECT * FROM daily_ridership")
print(c.fetchone())
print(c.fetchmany(2))
for record_id, date, season, working_day, rides in c:
    print(date, rides)
(1, '2011-01-01', 'Winter', 0, 985)
[(2, '2011-01-02', 'Winter', 0, 801), (3, '2011-01-03', 'Winter', 1, 1349)]
2011-07-04 6043
2011-07-05 4665
2011-07-06 4629

The names of the columns of the last query are in c.description.
Each item describes one column, and its first value is the name:

c.execute(
    """
        SELECT observation_date, total_rides
        FROM daily_ridership
    """
)
print([column[0] for column in c.description])
['observation_date', 'total_rides']

The list in brackets is a list comprehension, from objects and generator expressions:
the first item of each column description, for every column.

Check yourself: this code was run:

c.execute(
    """
        SELECT total_rides FROM daily_ridership
        WHERE record_id = 1
    """
)

What does c.fetchone() return?

A: (985,)

Correct: fetchone returns the first row as a tuple. The row has one column, so the tuple has one value; Python writes it with a comma, (985,), to show that the brackets are a tuple and not a parenthesized number.

B: 985

The thinking: the query returns one value, so we get that value.

The mistake: a row is always a tuple, even when it has a single value.
The answer is (985,), a tuple with one value (the comma shows that it is a tuple).
To get the number, write c.fetchone()[0].

C: [(985,)]

The thinking: the answer to a query is a list of rows.

The mistake: that is what fetchall() returns. fetchone() returns only the first row, without the list.

Practice

Your turn. Use the cursor c to read all the columns of the rows whose season is 'Winter', and print each row on its own line, as a tuple.

# your code here
Show a solution
c.execute(
    "SELECT * FROM daily_ridership WHERE season = 'Winter'"
)
for row in c.fetchall():
    print(row)
(1, '2011-01-01', 'Winter', 0, 985)
(2, '2011-01-02', 'Winter', 0, 801)
(3, '2011-01-03', 'Winter', 1, 1349)

The query asks for the winter rows, and the loop prints the rows that fetchall returns, one on each line.

Show a common mistake and why it happens

Here the whole list is printed with one print, so everything appears on a single line, inside square brackets.
To print the rows one on each line, loop over them.

c.execute("SELECT * FROM daily_ridership WHERE season = 'Winter'")
print(c.fetchall())
Show a common mistake and why it happens

fetchone takes only the next row, so only the first winter row is printed.
To get all of them, use fetchall or loop over the cursor.

c.execute("SELECT * FROM daily_ridership WHERE season = 'Winter'")
print(c.fetchone())

Passing values: parameters

A program usually asks about a value that it has in a variable, such as a season that the user chose.
A tempting way is to paste the value into the SQL text with an f-string.
This is dangerous, and the next box shows why. Suppose the text arrives from a user, and a user types a season that contains a bit of SQL:
In the examples below we write c.execute(...).fetchone() in one line:
execute returns the cursor itself, so we can call fetchone on the result.

season = "Summer' OR '1'='1"
query = f"""
    SELECT COUNT(*)
    FROM daily_ridership
    WHERE season = '{season}'
"""
print(query)
print(c.execute(query).fetchone())

    SELECT COUNT(*)
    FROM daily_ridership
    WHERE season = 'Summer' OR '1'='1'

(6,)

The query counts all six rows, not the rows of a season: the pasted text closed the quote and added a condition that is always true.
When the pasted text can change the structure of the query, this is called SQL injection, and it is a real way that attackers read or damage databases (in some programs the pasted text can also change or delete data, not only read it).

Here is a case that matters. A university website lets a student see their own grade by typing an ID number.
The program looks the ID up in a table grades, and the function my_grade pastes the typed ID into the query with an f-string, as the season was pasted.
The students and the ID numbers are invented; the ID is text, because an ID number can start with zeros.
The function prints the query, so that its structure is visible:

conn.executescript("""
CREATE TABLE grades (student_id TEXT, name TEXT, grade INTEGER);
INSERT INTO grades VALUES
    ('000000011', 'Ada Example', 91),
    ('000000012', 'Ben Sample', 74),
    ('000000013', 'Cleo Demo', 88),
    ('000000014', 'Dov Placeholder', 65);
""")

def my_grade(student_id):
    query = f"SELECT * FROM grades WHERE student_id = '{student_id}'"
    print(query)
    return c.execute(query).fetchall()

for row in my_grade('000000012'):
    print(row)
for row in my_grade("0' OR '1'='1"):
    print(row)
SELECT * FROM grades WHERE student_id = '000000012'
('000000012', 'Ben Sample', 74)
SELECT * FROM grades WHERE student_id = '0' OR '1'='1'
('000000011', 'Ada Example', 91)
('000000012', 'Ben Sample', 74)
('000000013', 'Cleo Demo', 88)
('000000014', 'Dov Placeholder', 65)

The first call returns one row, the row of the student who typed the ID.
The second text is not an ID: it closes the quote and adds a condition that is always true, so the query returns the rows of all the students.
The person typing decided what the program asks: this is a leak of private data, and the same hole can also change it, as we said above.

The safe way is a parameterized query. Write a question mark ? in the SQL where a value belongs, and give the values separately, in a tuple, as the second argument of execute.
SQLite treats the values only as data, never as SQL:

print(
    c.execute(
        """
            SELECT COUNT(*)
            FROM daily_ridership
            WHERE season = ?
        """,
        (season,)
    ).fetchone()
)
print(
    c.execute(
        """
            SELECT COUNT(*)
            FROM daily_ridership
            WHERE season = ?
        """,
        ('Summer',)
    ).fetchone()
)
print(
    c.execute(
        """
            SELECT observation_date
            FROM daily_ridership
            WHERE total_rides > ?
            AND working_day = ?
        """,
        (4600, 1)
    ).fetchall()
)
(0,)
(3,)
[('2011-07-05',), ('2011-07-06',)]

The strange text now finds no season of that name, so the count is 0, and the real season gives 3.
The values go in a tuple even when there is only one, which is why (season,) has a comma.
The question marks are filled in order. A placeholder stands for a value only:
not for a table name or a column name.

The same fix protects the grades lookup: in my_grade, the ID travels as a value, and the strange text is only an ID that no student has, so nothing comes back.

query = "SELECT * FROM grades WHERE student_id = ?"
print(c.execute(query, ("0' OR '1'='1",)).fetchall())
[]

Check yourself: which call is safe for a season that comes from a user?

A: c.execute("... WHERE season = ?", (season,))

Correct: the value travels separately from the SQL, so it can never change the structure of the query.

B: c.execute("... WHERE season = '" + season + "'")

The thinking: it builds the query from the pieces.

The mistake: joining text with + pastes the value into the SQL exactly as the f-string did, so the same injection works.

C: c.execute(f"... WHERE season = '{season.upper()}'")

The thinking: changing the text first makes it safe.

The mistake: a function applied to the text does not remove quotes or SQL words.
The pasted value is still part of the SQL.

Practice

Your turn. Write one query that gets the season through a ? parameter, and run it with 'Summer'.
Print the dates (the date text only) of the days with more than 4650 rentals, one date on each line.
The number 4650 is written inside the SQL.

# your code here
Show a solution
query = """
    SELECT observation_date
    FROM daily_ridership
    WHERE season = ?
    AND total_rides > 4650
"""
for row in c.execute(query, ('Summer',)):
    print(row[0])
2011-07-04
2011-07-05

The season is the only value that comes through the parameter.
Each row has one column, so row[0] is the date text.

Show a common mistake and why it happens

The condition on the rentals is missing, so every summer day is printed.
The parameter only replaces the season; the other conditions must still be written in the SQL.

query = "SELECT observation_date FROM daily_ridership WHERE season = ?"
for row in c.execute(query, ('Summer',)):
    print(row[0])
Show a common mistake and why it happens

Each row is a tuple, even when it has one value, so printing the row shows the brackets and the comma.
Take the value with row[0].

query = """
    SELECT observation_date
    FROM daily_ridership
    WHERE season = ?
    AND total_rides > 4650
"""
for row in c.execute(query, ('Summer',)):
    print(row)

Changing data and saving it

UPDATE, INSERT and DELETE work through execute too, with parameters.
A change is kept in a temporary state until you decide: conn.commit() saves it, and conn.rollback() cancels everything since the last commit.
The attribute c.rowcount says how many rows the last statement changed:

c.execute(
    """
        UPDATE daily_ridership
        SET total_rides = ?
        WHERE record_id = ?
    """,
    (990, 1)
)
print(c.rowcount)
print(
    c.execute(
        """
            SELECT total_rides
            FROM daily_ridership
            WHERE record_id = 1
        """
    ).fetchone()
)
conn.rollback()
print(
    c.execute(
        """
            SELECT total_rides
            FROM daily_ridership
            WHERE record_id = 1
        """
    ).fetchone()
)
1
(990,)
(985,)

The first answer shows the new value, because the connection sees its own change.
After rollback() the old value is back. With conn.commit() instead, the change would stay in the database, and in a file database it would remain after the program ends.
A change that was not committed before conn.close() is lost.

To add many rows with one statement, give executemany a list of tuples:

c.executemany(
    "INSERT INTO daily_ridership VALUES (?, ?, ?, ?, ?)",
    [
        (188, '2011-07-07', 'Summer', 1, 4592),
        (189, '2011-07-08', 'Summer', 1, 4040),
    ]
)
conn.commit()
print(
    c.execute(
        "SELECT COUNT(*) FROM daily_ridership"
    ).fetchone()[0]
)
8

Rows with names

A tuple needs you to remember that the fifth value is the rentals.
If you set conn.row_factory = sqlite3.Row, every row you fetch can also be read by column name, like a dictionary, and still unpacked like a tuple:
A connection has its own execute, a shortcut that creates a cursor for you, so conn.execute(...) works like c.execute(...).
The method keys() lists the names of the columns of a row.

conn.row_factory = sqlite3.Row
row = conn.execute(
    "SELECT * FROM daily_ridership WHERE record_id = 185"
).fetchone()
print(row['season'], row['total_rides'], row.keys())
Summer 6043 ['record_id', 'observation_date', 'season', 'working_day', 'total_rides']

This is close to what an ORM gives you: each row is something with named parts.
An ORM goes one step further: each row is an object with attributes, such as day.total_rides, so the code reads like the question (see the ORM lesson).

Practice

Your turn. Ask SQL, with MAX, for the largest number of rentals among the rows whose season is 'Winter', and print only that number (not the row).

# your code here
Show a solution
print(
    conn.execute(
        """
            SELECT MAX(total_rides)
            FROM daily_ridership
            WHERE season = 'Winter'
        """
    ).fetchone()[0]
)
1349

MAX returns a single row with a single value, and [0] takes the value out of the row.

Show a common mistake and why it happens

Without the WHERE condition, MAX looks at all the days, so the summer maximum is printed.
The season has to be chosen inside the SQL.

print(
    conn.execute("SELECT MAX(total_rides) FROM daily_ridership").fetchone()[0]
)
Show a common mistake and why it happens

SQLite compares text with = exactly, including capital letters, so no row has the season 'winter'.
MAX of no rows is NULL, which Python shows as None.

print(
    conn.execute(
        "SELECT MAX(total_rides) FROM daily_ridership WHERE season = 'winter'"
    ).fetchone()[0]
)

Let the database do the work

The database is built to filter and sum, so ask it for the answer instead of fetching everything and looping in Python.
Compare two ways to get the average rentals of a season. The SQL function AVG (from the SQL guide) averages the values of a column, so the database can compute the average itself:

def average_in_python(conn, season):
    rows = conn.execute(
        """
            SELECT total_rides
            FROM daily_ridership
            WHERE season = ?
        """,
        (season,)
    ).fetchall()
    return sum(row[0] for row in rows) / len(rows)

def average_in_sql(conn, season):
    return conn.execute(
        """
            SELECT AVG(total_rides)
            FROM daily_ridership
            WHERE season = ?
        """,
        (season,)
    ).fetchone()[0]

print(average_in_python(conn, 'Summer'))
print(average_in_sql(conn, 'Summer'))
4793.8
4793.8

Both give the same number (the average of the five summer days, 4793.8).
The first moves every row from the database into Python, which is fine for six rows and slow for millions.
The second moves one number. In general: filter, group and summarize in SQL, and use Python for what SQL cannot do, such as formatting, drawing, and the many steps that follow.

Do not forget to close the connection when you finish: conn.close().
Closing does not save: commit first.

Practice

Each question has its own code box: write your answer there and select Run.
Open a hint if you are stuck, and the solution only after you try.

Question 1. Print the dates and rentals of the working days (working_day is 1) with more than 4600 rentals, from the busiest day down.
Use a parameter for the number 4600. Print each day on its own line:
the date, a space, the rentals.

# your answer here
Show a first hint

Write the SQL first, as you would in DB Browser: which columns, which conditions and which order.
The number 4600 will become a question mark.

Show a second hint

The SQL is:

SELECT observation_date, total_rides
FROM daily_ridership
WHERE working_day = 1 AND total_rides > ?
ORDER BY total_rides DESC

Give (4600,) as the values.

Show a solution
sql = """
    SELECT observation_date, total_rides
    FROM daily_ridership
    WHERE working_day = 1
    AND total_rides > ?
    ORDER BY total_rides DESC
"""
for date, rides in conn.execute(sql, (4600,)):
    print(date, rides)
2011-07-05 4665
2011-07-06 4629

Two working days pass the condition. The working days of the winter, and the later summer days that we added, have fewer than 4600 rentals.

Show a common mistake and why it happens

ORDER BY sorts from the smallest by default. For the busiest day first, add DESC:

sql = """
    SELECT observation_date, total_rides
    FROM daily_ridership
    WHERE working_day = 1
    AND total_rides > ?
    ORDER BY total_rides
"""
for date, rides in conn.execute(sql, (4600,)):
    print(date, rides)

Question 2. Write a function season_count(conn, season) that returns how many rows a season has, with one SQL query and a parameter.
Print the counts of 'Winter' and 'Summer' on one line, separated by a space.

# your answer here
Show a solution
def season_count(conn, season):
    return conn.execute(
        """
            SELECT COUNT(*)
            FROM daily_ridership
            WHERE season = ?
        """,
        (season,)
    ).fetchone()[0]

print(
    season_count(conn, 'Winter'), season_count(conn, 'Summer')
)
3 5

The summer has 5 rows because the two rows that we added are also summer days.

Show a common mistake and why it happens

The parameter season is never used, so the query counts all the rows.
The value belongs in WHERE season = ? with (season,):

def season_count(conn, season):
    return conn.execute("SELECT COUNT(*) FROM daily_ridership").fetchone()[0]

print(season_count(conn, 'Winter'), season_count(conn, 'Summer'))

Question 3. Change the rentals of record 186 to 4700, check the new value, and then cancel the change.
Which value does the last read show, and why?

# your answer here
Show a solution
c.execute(
    """
        UPDATE daily_ridership
        SET total_rides = ?
        WHERE record_id = ?
    """,
    (4700, 186)
)
print(
    c.execute(
        """
            SELECT total_rides
            FROM daily_ridership
            WHERE record_id = 186
        """
    ).fetchone()
)
conn.rollback()
print(
    c.execute(
        """
            SELECT total_rides
            FROM daily_ridership
            WHERE record_id = 186
        """
    ).fetchone()
)
(4700,)
(4665,)

Before rollback() we see the new value, and after it the original.
The rows that we added with executemany were committed before, so the rollback does not remove them.

Keep in mind

  • A program works with a database in four steps: connect, cursor, execute, fetch. fetchall returns a list of tuples, fetchone one tuple or None, and a loop over the cursor takes the rows one at a time.
  • Pass values with ? placeholders and a tuple of values, never by pasting text into the SQL: pasting allows SQL injection.
  • A change is saved by commit() and cancelled by rollback(); executemany repeats a statement for a list of tuples.
  • sqlite3.Row lets you read a column by name.
  • Let SQL filter and summarize, and bring only the answer into Python.