Working with Databases in Python
Working with databases is a crucial part of software development. SQLite is one of the simplest and most powerful ways to store data in a local project. This lightweight database is built into Python and requires no separate server to run.
SQLite Basics
What It Is and How It Works
SQLite is an embedded relational database engine. It doesn't require installation or a separate server process. All data is stored in a single file. This makes SQLite an ideal choice for prototyping, desktop applications, and mobile apps.
Key Advantages
SQLite offers several important benefits:
• Built into Python via the sqlite3 module • No additional configuration needed • High performance for small to medium-sized projects • Simple and easy to use • Supports standard SQL queries • Small footprint with minimal system requirements
Use Cases for SQLite in Python
Common Scenarios
SQLite is widely used in the following situations:
• Learning projects and tutorials • Local applications and scripts • Small web apps, such as with Flask • Configuration storage systems • Offline programs with local data storage • Application prototyping • Data caching
Benefits for Developers
Python developers gain many advantages from using SQLite. The database requires no extra dependencies. It allows you to start working with relational data quickly. SQLite supports transactions and ensures data reliability.
Getting Started with SQLite
Importing and Connecting
SQLite is included in Python's standard library. Simply import the module to get started:
import sqlite3
Creating a Database Connection
Connecting to a Database File
conn = sqlite3.connect('example.db')
If the database file doesn't exist, it will be created automatically.
Working with an In-Memory Database
conn = sqlite3.connect(':memory:')
This database exists only in RAM. It is deleted when the program ends.
Creating a Database Structure
Creating Tables
cursor = conn.cursor()
cursor.execute('''
CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
age INTEGER,
email TEXT UNIQUE
)
''')
conn.commit()
Understanding Data Types
SQLite supports the following main data types:
• INTEGER - whole numbers • TEXT - text strings • REAL - floating-point numbers • BLOB - binary data • NULL - empty values
Data Operations
Inserting Data
Adding a Single Record
cursor.execute("INSERT INTO users (name, age, email) VALUES (?, ?, ?)",
("Alice", 25, "alice@example.com"))
conn.commit()
Inserting Multiple Records
users = [
("Bob", 30, "bob@example.com"),
("Charlie", 22, "charlie@example.com"),
("Diana", 28, "diana@example.com")
]
cursor.executemany("INSERT INTO users (name, age, email) VALUES (?, ?, ?)", users)
conn.commit()
Reading Data from the Database
Fetching All Records
cursor.execute("SELECT * FROM users")
rows = cursor.fetchall()
for row in rows:
print(row)