SQLite is a lightweight, serverless database engine that integrates seamlessly with Python. It's perfect for small to medium-sized applications and prototypes.
Python's built-in sqlite3
module provides a straightforward interface for working with SQLite databases. Let's dive into the basics:
To begin, import the module and establish a connection:
import sqlite3
conn = sqlite3.connect('example.db')
cursor = conn.cursor()
This creates a new database file named 'example.db' if it doesn't exist, or connects to it if it does.
Now, let's create a table and insert some data:
cursor.execute('''CREATE TABLE IF NOT EXISTS users
(id INTEGER PRIMARY KEY, name TEXT, email TEXT)''')
cursor.execute("INSERT INTO users (name, email) VALUES (?, ?)",
('John Doe', 'john@example.com'))
conn.commit()
The commit()
method saves the changes to the database.
Retrieving data is just as simple:
cursor.execute("SELECT * FROM users")
rows = cursor.fetchall()
for row in rows:
print(f"ID: {row[0]}, Name: {row[1]}, Email: {row[2]}")
conn.close()
with
statements for automatic connection managementSQLite in Python offers more advanced features for complex operations:
Ensure data integrity with transactions:
try:
conn.execute('BEGIN TRANSACTION')
# Perform multiple operations
conn.commit()
except sqlite3.Error:
conn.rollback()
Enable foreign key support for relational integrity:
conn.execute('PRAGMA foreign_keys = ON')
SQLite works well with various Python features:
Python's SQLite integration offers a powerful yet simple solution for database management. Whether you're building a small application or prototyping a larger system, mastering SQLite in Python can significantly enhance your development workflow.
For more complex database needs, consider exploring Python MySQL Connector or Python PostgreSQL integration.