Almost every application stores data: users, orders, grades, messages. A database stores them in an orderly way and lets you query them quickly. Python includes the sqlite3 module, to work with SQLite, a relational database engine that needs no installation and no server running.
Relational databases organize information in tables (like spreadsheets). They are handled with the SQL language.
| Concept | What it is | Example |
|---|---|---|
| Table | a set of data of the same kind | contacts |
| Column | a field of every element, with a type | name, phone |
| Row | a specific element | ('ana', '611') |
| Query | an SQL command | SELECT * FROM contacts |
Connecting to the database
sqlite3.connect(target) returns a connection. The target can be a file ("data.db", created if it does not exist and the data is kept) or the special string ":memory:", a temporary in-memory database that disappears when the program ends. This lesson uses ":memory:" so that the examples are always the same.
import sqlite3
con = sqlite3.connect(":memory:")
print(type(con).__name__) # Connection
con.close()
Creating a table
CREATE TABLE defines the columns and their types. The main ones: INTEGER (whole numbers), REAL (decimals), TEXT (text) and BLOB (binary data). Python converts them automatically: int, float, str, bytes and None (which is NULL, absence of a value).
import sqlite3
con = sqlite3.connect(":memory:")
con.execute("CREATE TABLE contacts (name TEXT, phone TEXT)")
print("table created") # table created
Inserting rows
Values are passed separately, with ? placeholders and a tuple. The engine puts them in place (in article 3 you will see why this matters).
import sqlite3
con = sqlite3.connect(":memory:")
con.execute("CREATE TABLE contacts (name TEXT, phone TEXT)")
con.execute("INSERT INTO contacts VALUES (?, ?)", ("ana", "611"))
con.execute("INSERT INTO contacts VALUES (?, ?)", ("luis", "600"))
rows = [("bea", "622"), ("eva", "633")]
con.executemany("INSERT INTO contacts VALUES (?, ?)", rows) # several at once
print(con.execute("SELECT COUNT(*) FROM contacts").fetchone()) # (4,)
Reading the results
execute returns a cursor. You can loop over it with for, or ask for the results with fetchall() (list of tuples) and fetchone() (the next row, or None if there are no more).
import sqlite3
con = sqlite3.connect(":memory:")
con.execute("CREATE TABLE contacts (name TEXT, phone TEXT)")
con.executemany("INSERT INTO contacts VALUES (?, ?)", [("ana", "611"), ("luis", "600"), ("bea", "622")])
cursor = con.execute("SELECT name, phone FROM contacts ORDER BY name")
print(cursor.fetchall()) # [('ana', '611'), ('bea', '622'), ('luis', '600')]
total = con.execute("SELECT COUNT(*) FROM contacts").fetchone()[0]
print(total) # 3
for name, phone in con.execute("SELECT name, phone FROM contacts ORDER BY name"):
print(f"{name}: {phone}")
# ana: 611
# bea: 622
# luis: 600
print(con.execute("SELECT * FROM contacts WHERE name = ?", ("nobody",)).fetchone()) # None
Put it into practice with Contact book.
An order that is not guaranteed
Without ORDER BY, SQL does not promise any order in the results. If the order matters (for example, to show or compare), always state it.
Closing the connection
When finished, con.close() releases the connection. With in-memory databases it makes no difference, but with files it is a good habit.