Python's built-in sqlite3 module provides a straightforward interface for working with SQLite databases. No additional installation is required since it's included in Python's standard library.
Basic Connection Setup
To establish a connection, import the module and use sqlite3.connect() with either a database file path or :memory: for an in-memory database:
import sqlite3
# Connect to a file-based database
conn = sqlite3.connect('example.db')
# Or create an in-memory database
conn = sqlite3.connect(':memory:')
Creating a Cursor
After connecting, create a cursor object to execute SQL commands:
cursor = conn.cursor()
Executing SQL Commands
Use the cursor to run SQL statements. For data retrieval, use execute() followed by fetchone(), fetchall(), or fetchmany():
# Create a table
cursor.execute('''CREATE TABLE IF NOT EXISTS users
(id INTEGER PRIMARY KEY, name TEXT, email TEXT)''')
# Insert data
cursor.execute("INSERT INTO users (name, email) VALUES (?, ?)",
("John Doe", "[email protected]"))
# Query data
cursor.execute("SELECT * FROM users")
results = cursor.fetchall()
Best Practices
Always use parameterized queries (with ? placeholders) to prevent SQL injection attacks. Handle the connection properly using context managers:
with sqlite3.connect('example.db') as conn:
cursor = conn.cursor()
cursor.execute("SELECT * FROM users")
data = cursor.fetchall()
# Connection automatically closes
Error Handling
Wrap database operations in try-except blocks to handle potential errors:
try:
conn = sqlite3.connect('example.db')
# Database operations here
except sqlite3.Error as e:
print(f"Database error: {e}")
finally:
if conn:
conn.close()
Remember to commit transactions using conn.commit() for data modifications and always close connections when finished to free resources.