HOME HTML EDITOR C JAVA PHP python

Python SQLite

SQLite is a lightweight, serverless, file-based relational database built directly into Python via the sqlite3 module. No separate database server or third-party installation is needed, making it ideal for local apps, scripts, prototyping, and testing.

1. Connecting to SQLite & Creating a Table

Call sqlite3.connect() to open (or create) a database file, execute SQL with a cursor, and commit changes:

import sqlite3

conn = sqlite3.connect("expertsjava.db")
cursor = conn.cursor()

cursor.execute("""
    CREATE TABLE IF NOT EXISTS tasks (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        title TEXT NOT NULL,
        completed INTEGER DEFAULT 0
    )
""")
conn.commit()

2. Parameterized INSERT & SELECT

Use ? placeholders with a tuple of parameters to safely insert data and query rows with fetchall():

cursor.execute(
    "INSERT INTO tasks (title, completed) VALUES (?, ?)",
    ("Finish Python SQLite page", 1)
)
conn.commit()

cursor.execute("SELECT id, title, completed FROM tasks")
for row in cursor.fetchall():
    print(row)

3. Updating & Deleting Records

Update or delete specific records using a WHERE clause, then close the connection when finished:

cursor.execute(
    "UPDATE tasks SET completed = ? WHERE title = ?",
    (1, "Finish Python SQLite page")
)
cursor.execute(
    "DELETE FROM tasks WHERE id = ?",
    (1,)
)
conn.commit()

conn.close()
Tip: Passing ":memory:" to sqlite3.connect(":memory:") creates a temporary database in RAM — great for fast unit tests that clean up automatically.