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

Steps

  1. Create a file called notes.py and 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.

  1. 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.

  1. 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.

  1. 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.

  1. Close the connection:
conn.close()
  1. Run it with python3 notes.py and type a note when asked. Run it again and add another; both should be listed.

How to check it worked

Common mistakes

MistakeSymptomFix
Forgetting commit()New notes disappearCall conn.commit() after changes
Building SQL with f-stringsWorks, but unsafeAlways use ? placeholders
(new_note) without a commaError about the number of bindingsWrite (new_note,)
Running from a different folderA new empty notes.db appearsUse 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.

Related pages on this site