Python supplies the values and decides what happens next.
Gregory S. DeLozier, PhD
The script rebuilds the pet table on every run.
import argparse
import sqlite3
ap = argparse.ArgumentParser()
ap.add_argument("--db", default="pets.db")
args = ap.parse_args()
connection = sqlite3.connect(args.db)args.db supplies the filename.
Python calls the method. SQLite interprets the string.
cursor = connection.execute("""
SELECT name FROM sqlite_master
WHERE type = 'table' ORDER BY name
""")
list_of_tables = [item[0] for item in cursor.fetchall()]['pet', 'sqlite_sequence']
connection.execute(
"INSERT INTO pet (name, kind, age, food) "
"VALUES (?, ?, ?, ?)",
("Dorothy", "dog", 11, "peanut butter"),
)Four placeholders. Four values, in the same order.
connection.execute(
"INSERT INTO pet (name, kind, age, food) "
"VALUES (?, ?, ?, ?)",
("Whiskers", "hamster", 1, "hamster chow"),
)
connection.commit()Dorothy and Whiskers precede this commit.
(1, 'Dorothy', 'dog', 11, 'peanut butter')
A stored record becomes a Python tuple.
cursor = connection.execute(
"SELECT name FROM pet ORDER BY id"
)
first = cursor.fetchone()
rest = cursor.fetchall()first: ('Dorothy',)
rest: [('Whiskers',)]
cursor = connection.execute(
"SELECT sql FROM sqlite_master "
"WHERE type='table' AND name=?",
("pet",),
)
row = cursor.fetchone()
pprint(row[0] if row else "")("pet",) is a tuple. ("pet") is a
string.
try with a wrong name
Caught sqlite error: no such table: petz
Caught sqlite error: no such table: petz
Catching the exception lets the program continue.
Repeating the same misspelling fails again.
The condition can match more than one record.
connection.execute(
"UPDATE pet SET age=?, food=? WHERE name=?",
(12, "pretzels", "Dorothy"),
)
connection.commit()SET supplies changes. WHERE selects
records.
| id | name | kind | age | food |
|---|---|---|---|---|
| 1 | Dorothy | dog | 12 | pretzels |
| 2 | Whiskers | hamster | 1 | hamster chow |
| 3 | Sandy | cat | 9 | tuna |
| 4 | Maxwell | cat | 11 | tuna |
A new process can retrieve these records.
connection = sqlite3.connect("practice.db")
try:
cursor = connection.execute(
"SELECT name FROM pet ORDER BY name"
)
pprint(cursor.fetchall())
finally:
connection.close()Closing is not a substitute for committing.