Reading history

Python SQLite3 Database Tutorial With Examples

6 min read 1 views

Use Python's built-in sqlite3 module: create tables, insert with placeholders, query rows, transactions with rollback, sqlite3.Row and SQL injection safety.

Python comes with SQLite, a complete database engine that keeps all its data in a single file. There is no server to install, and the built-in sqlite3 module lets you create tables, insert rows and run SQL queries straight from Python. It is ideal for desktop apps, small websites, tests and learning SQL. This lesson covers connecting, inserting with placeholders, querying, transactions and protecting against SQL injection.

In this lesson you will learn

  • Connecting to a database and creating a table
  • Inserting rows safely with ? placeholders and executemany
  • Reading rows with fetchone, fetchall and loops
  • Transactions: commit, rollback and with con:
  • Getting dictionary-like rows with sqlite3.Row

You should know exception handling and context managers. Some SQL helps; see our SQL SELECT lesson.

Creating, Inserting and Querying

import sqlite3

# ":memory:" makes a temporary database; use a file name like "shop.db" to keep it
con = sqlite3.connect(":memory:")
cur = con.cursor()

cur.execute("""
    CREATE TABLE products (
        id    INTEGER PRIMARY KEY,
        name  TEXT NOT NULL,
        price REAL NOT NULL,
        stock INTEGER DEFAULT 0
    )
""")

# ? placeholders keep data separate from the SQL text
cur.execute("INSERT INTO products (name, price, stock) VALUES (?, ?, ?)", ("Notebook", 60, 120))
print("new row id:", cur.lastrowid)
items = [("Pen", 15, 500), ("Calculator", 850, 12), ("Geometry Box", 180, 40)]
cur.executemany("INSERT INTO products (name, price, stock) VALUES (?, ?, ?)", items)
con.commit()                     # save the changes

for row in cur.execute("SELECT id, name, price FROM products ORDER BY price"):
    print(row)

cur.execute("SELECT name, stock FROM products WHERE price < ?", (100,))
print("cheap:", cur.fetchall())

cur.execute("UPDATE products SET stock = stock - ? WHERE name = ?", (2, "Calculator"))
print("rows updated:", cur.rowcount)
cur.execute("SELECT COUNT(*), SUM(price * stock) FROM products")
count, value = cur.fetchone()
print(f"{count} products, stock worth {value:,.0f} taka")
con.close()

Output

new row id: 1
(2, 'Pen', 15.0)
(1, 'Notebook', 60.0)
(4, 'Geometry Box', 180.0)
(3, 'Calculator', 850.0)
cheap: [('Notebook', 120), ('Pen', 500)]
rows updated: 1
4 products, stock worth 30,400 taka
  • sqlite3.connect(":memory:") opens a temporary database that disappears when the program ends. Give a file name such as "shop.db" instead, and the file is created if it does not exist.
  • A cursor runs SQL with execute. INTEGER PRIMARY KEY makes id number itself, and lastrowid tells you the id of the row just inserted.
  • The ? marks are placeholders. The values are passed separately as a tuple, and SQLite inserts them safely. executemany runs the same statement once for each tuple in a list.
  • con.commit() saves the changes. Changes that are not committed are lost when the connection closes.
  • Looping over cur.execute(...) gives each row as a tuple. fetchall() returns all rows as a list, and fetchone() returns just the next row, handy for COUNT and SUM.
  • A one-item tuple needs a trailing comma: (100,). rowcount reports how many rows an UPDATE or DELETE changed.

Transactions, Row Objects and SQL Injection

import sqlite3

con = sqlite3.connect(":memory:")
con.row_factory = sqlite3.Row          # rows behave like dicts
con.execute("CREATE TABLE accounts (name TEXT PRIMARY KEY, balance INTEGER CHECK (balance >= 0))")
con.executemany("INSERT INTO accounts VALUES (?, ?)", [("Rina", 5000), ("Karim", 1000)])
con.commit()

def transfer(sender, receiver, amount):
    try:
        with con:                      # commits on success, rolls back on error
            con.execute("UPDATE accounts SET balance = balance + ? WHERE name = ?", (amount, receiver))
            con.execute("UPDATE accounts SET balance = balance - ? WHERE name = ?", (amount, sender))
        print(f"sent {amount} from {sender} to {receiver}")
    except sqlite3.IntegrityError as e:
        print(f"transfer of {amount} failed: {e}")

def show():
    for row in con.execute("SELECT * FROM accounts ORDER BY name"):
        print(f"  {row['name']}: {row['balance']}")

transfer("Rina", "Karim", 1500)
transfer("Karim", "Rina", 9000)        # would make Karim negative
show()

# Why placeholders matter: a name typed by a user
evil = "x' OR '1'='1"
unsafe = f"SELECT COUNT(*) FROM accounts WHERE name = '{evil}'"
print("string-built query matches", con.execute(unsafe).fetchone()[0], "rows")
safe = con.execute("SELECT COUNT(*) FROM accounts WHERE name = ?", (evil,)).fetchone()[0]
print("placeholder query matches", safe, "rows")
con.close()

Output

sent 1500 from Rina to Karim
transfer of 9000 failed: CHECK constraint failed: balance >= 0
  Karim: 2500
  Rina: 3500
string-built query matches 2 rows
placeholder query matches 0 rows
  • con.row_factory = sqlite3.Row makes each row readable by column name, as in row["balance"].
  • A money transfer is two updates that must both happen or both fail. with con: starts a transaction: if the block finishes, it commits; if an exception escapes, it rolls everything back.
  • The second transfer adds 9,000 to Rina first, then the CHECK (balance >= 0) rule rejects Karim’s new balance. The whole transaction is rolled back, so Rina’s extra 9,000 disappears too and the balances stay correct.
  • The last part shows SQL injection. Building the query with an f-string lets the text ' OR '1'='1 become part of the SQL, so the query matches every row. With a placeholder, the same text is treated as an ordinary name and matches nothing.

sqlite3 Cheat Sheet

TaskCode
Open or create a databasecon = sqlite3.connect("app.db")
Run one statementcon.execute(sql, (a, b))
Run for many rowscon.executemany(sql, list_of_tuples)
Read rowsfetchone(), fetchall(), or loop over the cursor
Save changescon.commit() or with con:
Rows by column namecon.row_factory = sqlite3.Row
Finishcon.close()

Common Mistakes

  1. Building SQL with f-strings or + from user input. Always use placeholders.
  2. Forgetting to commit, so the data seems to save but is gone next time.
  3. Writing (5) instead of (5,) for one parameter. Without the comma it is not a tuple.
  4. Thinking with con: closes the connection. It only commits or rolls back; call close() yourself.

Practice Exercises

Exercise 1. Add a query to the products example that lists products with less than 50 items in stock, lowest first.

Show answer
rows = cur.execute(
    "SELECT name, stock FROM products WHERE stock < ? ORDER BY stock", (50,)
).fetchall()
print(rows)   # [('Calculator', 10), ('Geometry Box', 40)]

Exercise 2. Write delete_product(con, name) that deletes a product by name inside a transaction and returns how many rows were deleted.

Show answer
def delete_product(con, name):
    with con:
        cur = con.execute("DELETE FROM products WHERE name = ?", (name,))
    return cur.rowcount

Frequently Asked Questions

When should I use a bigger database such as PostgreSQL or MySQL?

When many users write at the same time over a network, or the data grows very large. SQLite handles many readers well but lets only one writer at a time, which is fine for most small and medium apps.

How can I look at an SQLite file?

Use the sqlite3 command-line tool or a free program such as DB Browser for SQLite. Both open the .db file directly and let you browse tables and run queries.

Summary

  • sqlite3 gives Python a full SQL database in a single file.
  • Use ? placeholders for every value: they are both correct and safe.
  • Commit to save; use with con: so a failure rolls back the whole change.
  • sqlite3.Row lets you read columns by name.

Next: Python Threading and concurrent.futures.

Lessons are also marked complete when you click Next.

Leave a Reply

Your email address will not be published. Required fields are marked *