Sqlite3 Tutorial Query Python Fixed Page

SQLite3 Tutorial: Querying with Python

SQLite is a lightweight disk-based database that doesn’t require a separate server process. It's a popular choice for small to medium-sized projects, and its ease of use makes it a great introduction to database programming. In this tutorial, we'll focus on using SQLite3 with Python, covering the basics of querying a database.

3) Insert safely (parameterized)

# single
cur.execute("INSERT INTO users (name, email) VALUES (?, ?)", ("Alice", "alice@example.com"))
# multiple
users = [("Bob","bob@example.com"), ("Eve","eve@example.com")]
cur.executemany("INSERT INTO users (name, email) VALUES (?, ?)", users)
with get_db_connection() as conn: cursor = conn.cursor() cursor.execute(query, user_ids) return [dict(row) for row in cursor.fetchall()]

Creating Tables

def create_tables():
    conn = sqlite3.connect('my_database.db')
    cursor = conn.cursor()
# Create users table
cursor.execute('''
    CREATE TABLE IF NOT EXISTS users (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        username TEXT NOT NULL UNIQUE,
        email TEXT NOT NULL UNIQUE,
        age INTEGER,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
    )
''')
conn.close()