PYTHON · PYTHON FOR EVERYONE · CHAPTER 18

Databases

Store your network inventory in SQLite and query it from Python with transactions and injection-proof queries.

11 min readCourse: Python for EveryoneLevel: beginner

From point A to point B

Point A: you keep your network inventory in text, JSON or pickle files. It works with 20 devices, but with 2,000 you need to search, filter and update without rewriting the whole file. Point B: by the end of this chapter, you'll create an SQLite database from Python, insert and query devices and control transactions. You'll also write queries protected against SQL injection.

This chapter assumes you know basic SQL: CREATE TABLE, INSERT and SELECT. If you don't, review it first; the focus here is on how to use it from Python.

Why a database

Text, XML, JSON or pickle files work for many cases. But when the data grows or several programs use it at once, you hit limits. You need to search without loading everything into memory, avoid duplicates and keep 2 simultaneous writes from stepping on each other.

A relational database solves those problems. It organizes data into tables, guarantees consistency with rules like primary keys and groups changes into transactions. Plus, you query it with SQL, a language shared by almost every engine.

DB API 2.0: one common interface

There are dozens of database engines and, for each one, different Python modules. Without an agreement, you'd have to learn a different API for every engine.

Python defines a common specification: the Python Database API, or DB API, version 2.0, described in PEP 249. It's similar to JDBC in Java. A module that follows it offers the same functions and methods, so your code changes little if you switch engines.

In this chapter you'll use SQLite through the sqlite3 module. SQLite doesn't need a server: it's a C library that stores the whole database in a file. It comes with Python, so there's nothing to install or configure.

For other engines you install a connector from PyPI. They all follow DB API 2.0:

EnginePyPI packageNotes
MySQL / MariaDBmysqlclientFork of the old MySQLdb with Python 3 support. You import it as MySQLdb.
MySQL / MariaDBPyMySQLWritten entirely in Python, with nothing to compile.
PostgreSQLpsycopgPsycopg 3, successor to psycopg2. For new projects.
PostgreSQLpsycopg2Still published; use it if you maintain code that already depends on it.
Python 3.14 update. The book suggested MySQLdb for MySQL. That project doesn't support Python 3; its continuation is mysqlclient, which keeps the MySQLdb import name. For PostgreSQL, the current version is Psycopg 3 (the psycopg package). Install any of them with python -m pip install inside a virtual environment.

The global variables of a DB API module

Every DB API 2.0 compliant module publishes 3 variables that describe it:

  • apilevel: the DB API version it implements, "1.0" or "2.0".
  • threadsafety: an integer from 0 to 3 that tells you what you can share between threads. 0: not even the module; 1: the module, but not connections; 2: module and connections, but not cursors; 3: everything.
  • paramstyle: the syntax for inserting values into a query. You'll look at it in depth later on.
>>> import sqlite3
>>> sqlite3.apilevel
'2.0'
>>> sqlite3.threadsafety
3
>>> sqlite3.paramstyle
'qmark'
>>> sqlite3.sqlite_version
'3.53.1'

These are the 5 possible paramstyle styles. Each module uses one or more; sqlite3 supports qmark and named.

StyleExample
qmarkWHERE ip = ?
numericWHERE ip = :1
namedWHERE ip = :ip
formatWHERE ip = %s
pyformatWHERE ip = %(ip)s

Watch out: although format and pyformat look like Python string formats, they aren't the same thing. It's the connector that substitutes the value safely. You never apply % or f-strings to the query.

The exception hierarchy

The DB API also standardizes errors. That way you can catch them the same way whatever the engine. This is the hierarchy, with Exception at the root:

  • Exception
    • Warning: important warnings.
    • Error: base of all errors.
      • InterfaceError: failures in the module itself, not the database.
      • DatabaseError: database failures.
        • DataError: invalid data, like a division by 0 or an out-of-range value.
        • OperationalError: operational problems, like a disconnect or a locked file.
        • IntegrityError: integrity violations, like a duplicate key.
        • InternalError: internal engine error.
        • ProgrammingError: programming errors, like invalid SQL or a table that doesn't exist.
        • NotSupportedError: an operation the engine doesn't support.
>>> import sqlite3
>>> issubclass(sqlite3.IntegrityError, sqlite3.DatabaseError)
True
>>> issubclass(sqlite3.Error, Exception)
True

Catch the most specific exception you can handle. For example, IntegrityError when you try to insert a duplicate device, as you'll see shortly.

Connection, cursor and execute

The first step is to connect with connect(). Its parameters aren't standardized: they depend on the engine. In sqlite3 the file path is enough, or ":memory:" for a temporary database in RAM. A MySQL or PostgreSQL connector, on the other hand, asks for server, port, user, password and database name.

connect() returns a Connection object. To run SQL you need a cursor, which you get with cursor(). The cursor sends statements with execute() and walks through the results.

>>> import sqlite3
>>> con = sqlite3.connect(":memory:")
>>> con
<sqlite3.Connection object at 0x7fcd0489b100>
>>> cur = con.cursor()
>>> cur
<sqlite3.Cursor object at 0x7fcd046eafc0>
>>> con.close()

This script creates the inventory table, inserts a router and queries it:

import sqlite3

con = sqlite3.connect("inventory.db")   # creates the file if it doesn't exist
cur = con.cursor()

cur.execute("DROP TABLE IF EXISTS devices")
cur.execute("""
    CREATE TABLE devices (
        hostname TEXT PRIMARY KEY,
        ip       TEXT NOT NULL,
        type     TEXT,
        site     TEXT
    )
""")
cur.execute("""
    INSERT INTO devices VALUES ('r1', '10.0.0.1', 'router', 'Lima')
""")
con.commit()                            # commit the transaction

cur.execute("SELECT * FROM devices")
print(cur.fetchall())
cur.close()
con.close()
$ python3 create.py
[('r1', '10.0.0.1', 'router', 'Lima')]

When you're done, close the cursor and the connection with close(). That frees the file and the engine's resources.

Transactions: commit and rollback

A transaction groups changes that must all be applied together or not at all. Until you call commit() on the connection, the changes stay pending. rollback() discards them.

There's a detail that's confusing at first. From your own connection you see the pending changes, as if they were already saved. Another connection, however, doesn't see them until the commit:

import sqlite3

con = sqlite3.connect("inventory.db")
cur = con.cursor()
cur.execute("INSERT INTO devices VALUES ('sw9', '10.0.0.99', 'switch', 'Lima')")

other = sqlite3.connect("inventory.db")  # another connection, like an external tool
print("From this connection:", cur.execute("SELECT COUNT(*) FROM devices").fetchone())
print("From another connection:", other.execute("SELECT COUNT(*) FROM devices").fetchone())

con.rollback()                          # discard the pending INSERT
print("After rollback:", cur.execute("SELECT COUNT(*) FROM devices").fetchone())
other.close()
con.close()

The main connection counts 2 devices; the other, only 1. After the rollback, the pending device disappears.

$ python3 rollback.py
From this connection: (2,)
From another connection: (1,)
After rollback: (1,)

The DB API requires commit() to exist even in engines without transactions, even if it does nothing. That's why you should always call it: your code will stay correct if you switch engines. rollback(), on the other hand, only exists if the engine supports it.

In sqlite3, the connection also works as a context manager. When you leave the with con: block, it runs commit if everything went well, or rollback if there was an exception. executemany() runs the same statement with each element of a list:

import sqlite3

devices = [
    ("r2", "10.0.0.2", "router", "Bogotá"),
    ("sw1", "10.0.0.11", "switch", "Lima"),
    ("sw2", "10.0.0.12", "switch", "Bogotá"),
    ("fw1", "10.0.0.254", "firewall", "Lima"),
]

con = sqlite3.connect("inventory.db")
with con:                               # commit on exit; rollback on error
    con.executemany("INSERT INTO devices VALUES (?, ?, ?, ?)", devices)

try:
    with con:
        con.execute("INSERT INTO devices VALUES (?, ?, ?, ?)",
                    ("r1", "10.0.0.100", "router", "Quito"))
except sqlite3.IntegrityError as e:
    print("IntegrityError:", e)         # r1 already exists: it rolls back

print(con.execute("SELECT COUNT(*) FROM devices").fetchone()[0], "devices")
con.close()                             # `with con` doesn't close the connection
$ python3 insert.py
IntegrityError: UNIQUE constraint failed: devices.hostname
5 devices

The with con: commits or rolls back the transaction, but it doesn't close the connection. That's why the script calls close() at the end. con.execute() is a shortcut specific to sqlite3 (not part of the DB API) that creates a cursor and runs the statement in a single step.

Fact. Since Python 3.12, sqlite3.connect() accepts the autocommit parameter. The documentation recommends autocommit=False, which follows PEP 249 to the letter. The default in 3.14 is still sqlite3.LEGACY_TRANSACTION_CONTROL, the previous behavior, and it will change to False in a future version.

Reading results: fetchone, fetchmany and fetchall

Queries are also sent with execute(). Then the cursor hands you the rows as tuples with these methods:

  • fetchone(): the next row, or None if there are none left.
  • fetchmany(n): a list with the next n rows. With no argument, it uses cursor.arraysize, which is 1 by default.
  • fetchall(): a list with all the remaining rows.

You can also loop over the cursor directly with for. It's the most convenient way and it doesn't load every row into memory at once.

import sqlite3

con = sqlite3.connect("inventory.db")
cur = con.cursor()

cur.execute("SELECT hostname, ip FROM devices ORDER BY hostname")
print(cur.fetchone())                   # one row (or None if none are left)
print(cur.fetchmany(2))                 # the next 2
print(cur.fetchall())                   # all the remaining ones
print(cur.fetchone())                   # none left

print("Default arraysize:", cur.arraysize)

for hostname, ip in cur.execute("SELECT hostname, ip FROM devices WHERE type = ?",
                                ("router",)):
    print(f"{hostname:4} {ip}")         # the cursor is iterable
con.close()
$ python3 query.py
('fw1', '10.0.0.254')
[('r1', '10.0.0.1'), ('r2', '10.0.0.2')]
[('sw1', '10.0.0.11'), ('sw2', '10.0.0.12')]
None
Default arraysize: 1
r1   10.0.0.1
r2   10.0.0.2

If you'd rather access columns by name instead of by position, assign sqlite3.Row to row_factory. This example also uses the named style, with a dictionary of parameters:

import sqlite3

con = sqlite3.connect("inventory.db")
con.row_factory = sqlite3.Row           # rows accessible by column name
row = con.execute("SELECT * FROM devices WHERE hostname = :host",
                  {"host": "fw1"}).fetchone()
print(row["ip"], row["site"])
print(dict(row))
con.close()
$ python3 row_by_name.py
10.0.0.254 Lima
{'hostname': 'fw1', 'ip': '10.0.0.254', 'type': 'firewall', 'site': 'Lima'}

Parameterized queries against SQL injection

This is the most important rule in the chapter: never build an SQL query by gluing text together with +, %, format() or f-strings. If a value comes from the user, a form or an API, it can contain SQL that the engine will run. That attack is called SQL injection.

Picture an internal portal that lists the devices at a site with a URL like /devices?site=Lima. Someone enters Lima' OR '1'='1 as the site. The quote closes the string, and the condition OR '1'='1' is always true:

import sqlite3

con = sqlite3.connect("inventory.db")

site = "Lima' OR '1'='1"                # what an attacker types into a form

# WRONG: the user's text is glued into the SQL
query = f"SELECT hostname FROM devices WHERE site = '{site}'"
print(query)
print("Concatenated:", con.execute(query).fetchall())

# RIGHT: the value travels separately and is never interpreted as SQL
print("Parameterized:", con.execute(
    "SELECT hostname FROM devices WHERE site = ?", (site,)).fetchall())

try:
    con.execute("SELECT hostname FROM devices WHERE site = 'Lima'; DROP TABLE devices")
except sqlite3.ProgrammingError as e:
    print("ProgrammingError:", e)
con.close()
$ python3 injection.py
SELECT hostname FROM devices WHERE site = 'Lima' OR '1'='1'
Concatenated: [('r1',), ('r2',), ('sw1',), ('sw2',), ('fw1',)]
Parameterized: []
ProgrammingError: You can only execute one statement at a time.

The concatenated query returns the full inventory, not just Lima. The parameterized one literally looks for a site named Lima' OR '1'='1, finds none and returns an empty list. With parameters, the value travels separately from the statement and the engine never interprets it as SQL.

The last attempt shows an extra safeguard in sqlite3: execute() rejects several statements separated by ;. Don't rely on it: other engines and other attacks don't have that barrier. The only solid defense is to always parameterize.

Remember the 2 forms in sqlite3:

  • qmark: execute("... WHERE site = ?", (site,)). Notice the comma: a single value also goes inside a tuple.
  • named: execute("... WHERE site = :site", {"site": site}). In Python 3.14, using named placeholders and passing a sequence instead of a dictionary raises ProgrammingError.

Parameters replace values, not table or column names. If you need to pick a column based on user input, check it against a fixed list of allowed names.

Dates, times and binary data

The DB API defines constructors for special SQL types:

  • Date(year, month, day), Time(hour, minute, second) and Timestamp(year, month, day, hour, minute, second) for dates and times.
  • DateFromTicks, TimeFromTicks and TimestampFromTicks, which start from the seconds elapsed since the epoch (January 1, 1970 UTC).
  • Binary for binary data.

They exist in sqlite3, but they're just aliases for types you already know:

>>> import sqlite3
>>> sqlite3.Date(2026, 10, 24)
datetime.date(2026, 10, 24)
>>> sqlite3.Timestamp(2026, 10, 24, 3, 15, 0)
datetime.datetime(2026, 10, 24, 3, 15)
>>> sqlite3.Binary(b"\x00\x01")
<memory at 0x7fcd04933ac0>

SQLite has no date type of its own. The recommended practice is to store dates as ISO 8601 text with isoformat() and rebuild them with datetime.fromisoformat(). Binary data, like a configuration backup, is stored as bytes in a BLOB column:

import sqlite3
from datetime import datetime, timezone

con = sqlite3.connect(":memory:")
con.execute("CREATE TABLE backups (hostname TEXT, taken_at TEXT, config BLOB)")

now = datetime(2026, 10, 24, 3, 15, tzinfo=timezone.utc)
config = "hostname r1\ninterface Gi0/0\n ip address 10.0.0.1 255.255.255.0\n".encode()

with con:
    con.execute("INSERT INTO backups VALUES (?, ?, ?)",
                ("r1", now.isoformat(), config))     # date as ISO 8601 text

hostname, taken_at, blob = con.execute("SELECT * FROM backups").fetchone()
print(hostname, taken_at, type(blob).__name__, len(blob), "bytes")
print(datetime.fromisoformat(taken_at) == now)
con.close()
$ python3 backups.py
r1 2026-10-24T03:15:00+00:00 bytes 63 bytes
True
Python 3.14 update. The automatic date adapters and converters in sqlite3 have been deprecated since Python 3.12. That's why the example converts the date to text explicitly. In the book, Binary took a string; in Python 3 binary data is bytes. And the threadsafety value of sqlite3 is no longer fixed: since 3.11 it depends on how the SQLite library was compiled (in the test it was 3).

Other options: ORMs and non-relational databases

The DB API isn't the only way to work with data. An ORM (object-relational mapper) lets you handle tables as Python classes and rows as objects. The ORM generates the SQL for you and parameterizes it.

The best known is SQLAlchemy, which also offers a layer for writing engine-independent SQL. The book also mentioned SQLObject and Storm, which are still published on PyPI. For object databases there's ZODB.

An ORM saves repetitive code, but it adds a layer you also have to learn. Start by mastering the DB API: understanding which SQL runs helps you debug any ORM.

Challenge

Answer before you open the solution.

1. What's wrong with cur.execute(f"SELECT * FROM devices WHERE ip = '{ip}'")?

It's vulnerable to SQL injection. The value of ip is glued into the statement. Write cur.execute("SELECT * FROM devices WHERE ip = ?", (ip,)).

2. You insert a device, don't call commit() and query it from the same connection. Does it show up?

Yes, but only for that connection. Other connections don't see it, and if you close without commit() the change is lost.

3. What does with con: do in sqlite3, and what doesn't it do?

It commits or rolls back the transaction, but it doesn't close the connection. If the block ends without errors, it runs commit; if there's an exception, rollback. You have to call close() separately.

4. You insert a hostname that already exists in a PRIMARY KEY column. Which exception do you catch?

sqlite3.IntegrityError. It's a subclass of DatabaseError and signals that an integrity rule was violated, like a unique key.

5. Why doesn't execute("... WHERE site = ?", ("Lima")) work the way you expect?

Because ("Lima") isn't a tuple, it's a string. sqlite3 treats it as a sequence of 4 characters and raises ProgrammingError. Write ("Lima",), with the comma.

Key takeaways

  • DB API 2.0 (PEP 249) unifies database access: connect, cursor, execute, fetch*, commit and rollback.
  • sqlite3 comes with Python and stores the database in a file, with no server.
  • Changes aren't final until commit(); with con: does it for you, but it doesn't close the connection.
  • Always parameterize: ? or :name with a tuple or a dictionary. Never f-strings in SQL.
  • Store dates as ISO 8601 text and binary data as bytes.
  • For MySQL use mysqlclient or PyMySQL; for PostgreSQL, psycopg. To work with objects, an ORM like SQLAlchemy.

In the next chapter, you'll document your code with docstrings. That way other people, and you 6 months from now, will understand what each function does.

Official resources

Source and credits. This course is based on the book Python para todos by Raúl González Duque, published under the Creative Commons Attribution 2.5 Spain license. The original book was written for Python 2.5. Jesús Espinoza, with AI assistance, brought it to Python 3.14: he rewrote every chapter in his own words, replaced the examples with networking cases, updated the syntax and the modules that no longer exist, fixed errors in the original and tested all the code with Python 3.14.6 against the official documentation.

Navigate