Skip to content

Q&A · Answered

How to work with SQLite in Python

asked 9 months, 1 week ago 1605 views 1 answer
45

I need a simple database for my Python project. How do I use SQLite?

1 Answer

One accepted
20

Accepted answer

Not confirmed since it was written, 9 months, 1 week ago
import sqlite3

# Connect to database
conn = sqlite3.connect('database.db')
cursor = conn.cursor()

# Create table
cursor.execute('''
    CREATE TABLE IF NOT EXISTS users (
        id INTEGER PRIMARY KEY,
        name TEXT NOT NULL,
        email TEXT UNIQUE
    )
''')

# Insert data
cursor.execute('INSERT INTO users (name, email) VALUES (?, ?)',
               ('John', 'john@example.com'))
conn.commit()

# Query data
cursor.execute('SELECT * FROM users')
rows = cursor.fetchall()
for row in rows:
    print(row)

conn.close()

Your answer

Say what you tried, not only what worked — the next person needs the reasoning. Code goes in a fenced block.

Shown beside your answer and never checked, so it cannot be a name someone already has here.

No account needed to answer. Sign in instead and it carries your name and earns reputation.