45
I need a simple database for my Python project. How do I use SQLite?
Loading...
Q&A · Answered
I need a simple database for my Python project. How do I use SQLite?
Accepted answer
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()Say what you tried, not only what worked — the next person needs the reasoning. Code goes in a fenced block.