How to Connect a Python Script to SQLite
Python ships with a module called sqlite3, so you can use a real database from code without installing anything extra. This how-to writes a short script that creates a table, adds rows safely and reads them back.
What you need
- Python 3 installed (check with
python3 --versionorpython --version) - a text editor
- a folder for your practice files
Steps
- Create a file called
notes.pyand add:
import sqlite3
conn = sqlite3.connect("notes.db") # creates the file if needed
cur = conn.cursor()
connect opens the database file. A cursor is the object you use to send SQL and read results.
- Create a table if it does not exist yet:
cur.execute("""
CREATE TABLE IF NOT EXISTS notes (
id INTEGER PRIMARY KEY,
text TEXT NOT NULL
)
""")
IF NOT EXISTS means you can run the script many times without an error.
- Insert a row using a placeholder:
new_note = input("Write a note: ")
cur.execute("INSERT INTO notes (text) VALUES (?)", (new_note,))
conn.commit()
The ? is a placeholder. The value travels separately in the tuple (new_note,), which keeps you safe from SQL injection. The comma matters: (new_note,) is a one-item tuple. commit() saves the change; without it, the insert is lost when the script ends.
- Read everything back:
for row in cur.execute("SELECT id, text FROM notes ORDER BY id"):
print(row[0], row[1])
Each row is a tuple of the selected columns.
- Close the connection:
conn.close()
- Run it with
python3 notes.pyand type a note when asked. Run it again and add another; both should be listed.
How to check it worked
- The folder now contains
notes.db. - Each run lists all notes from earlier runs, which proves the data was saved.
- Open
notes.dbwith thesqlite3command-line tool and runSELECT * FROM notes;to see the same rows outside Python.
Common mistakes
| Mistake | Symptom | Fix |
|---|---|---|
Forgetting commit() | New notes disappear | Call conn.commit() after changes |
| Building SQL with f-strings | Works, but unsafe | Always use ? placeholders |
(new_note) without a comma | Error about the number of bindings | Write (new_note,) |
| Running from a different folder | A new empty notes.db appears | Use a full path or run from the same folder |
A tidier version with with
with sqlite3.connect("notes.db") as conn:
conn.execute("INSERT INTO notes (text) VALUES (?)", ("Tidy note",))
Used like this, the connection commits automatically if the block finishes without an error, and rolls back if one occurs. It does not close the connection, so still call close() when you are done.
Next steps
Try the same idea with a database server in how to use placeholders in Node.js, or learn why placeholders matter in our hands-on SQL injection exercise.
A free learning page for beginners. Practise on a test database, never on real customer data, and check the official documentation for your database version.