Python SQLite3 usage tutorial
SQLite is the most widely used embedded database engine in the world. It does not have the client/server architecture of a traditional database. Instead, it compresses the entire database system—including table structures, data, and indexes—into a cross-platform common file, which is very suitable for lightweight projects.
This tutorial will take you to master Python built-in modules from scratchsqlite3Core usage: Get started quickly with zero configuration, to advanced-features such as transactions and custom row factories, and finally consolidate what you have learned with complete examples and exercises.
1. Introduction to SQLite
SQLite has several major advantages that make it the lightweight database of choice for developers:
- 🚫 Zero server, zero configuration: No need to install database software, create one
.dbThe file can be used. - 🌐 Cross-platform: From mobile phones to servers, all mainstream platforms are available.
- 📝 Compatible with standard SQL: The learning cost is extremely low, and SQL syntax can be reused.
- 🐍 Python native built-in: Python 2.5 and above versions come directly with it
sqlite3Module, no additional installation required.
2. Pre-requisite core concepts
Before formally writing code, first understand the two core objects and a common operation process.
2.1 Core Objects
2.2 General operating procedures
No matter what operation you do, roughly follow these 6 steps (it will be simplified later using the context manager):
- Establish a connection to the database file
- Get the cursor object from the connection
- Execute SQL statements through cursors
- If it is a write operation (add, delete, modify), the transaction needs to be submitted
- Close the cursor (recommended)
- Close the connection (must be closed to avoid resource leakage)
3. Basic CRUD operations
We use the example of "User Management" to demonstrate addition, deletion, modification and query step by step.
3.1 Connect to database
If you just want to test temporarily and don't want to generate files, you can use:memory:Create an memory database and the data will disappear automatically after the program ends:
3.2 Create table
3.3 Insert data
⚠️ **Important! Never use string concatenation to populate SQL parameters! ** Must be used?Parameterized queries for placeholders + tuples to prevent SQL injection.
Single insert
Batch insert
executemany()Than loop callexecute()Much faster and recommended for batch writes:
3.4 Query data
There are three ways to obtain query results, choose as needed:
Get the full amount:fetchall()
Single item acquisition:fetchone()
Suitable for querying unique results (such as querying by ID or unique key):
Get in batches:fetchmany(n)
When querying large amounts of data, batch acquisition can avoid memory overflow caused by one-time loading:
3.5 Update data
3.6 Delete data
4. Advanced-features to improve development efficiency
4.1 Use context managers to automatically manage connections and transactions
Starting with Python 3.10,Connectionitself supportswithstatement, which has three benefits:
- Exit normally
withblock, automatically commit the transaction - When an exception occurs, automatically roll back the transaction
- After the block ends, automatically close the connection
Example:
4.2 Use row factory to return dictionary
The default query returns tuples without field names, which is inconvenient in many scenarios. Can be set byrow_factoryPut the results into a dictionary or more readable format.
Custom dictionary factory
Use the built-insqlite3.Row
If you don’t want to write your own factory, Python’s built-insqlite3.RowMore lightweight, also supports field name access:
4.3 Explicit control of transactions
Most of the time usewithIt is enough, but submission and rollback can also be manually controlled under complex business logic:
5. Best Practice Checklist
- ✅ Always use parameterized queries: Reject string concatenation SQL.
- ✅ Use
withStatement management connection: Automatically handle submission, rollback and closing to avoid resource leaks. - ✅ Batch operations are given priority
executemany(): Performance improvement is obvious. - ✅ Reasonable use of memory database: temporary testing or direct use of cache
:memory:。 - ✅ Capture
sqlite3.Error: Handle possible SQL syntax errors or constraint conflicts. - ✅ Consider ORM for complex applications: For example, SQLAlchemy can map tables into Python classes to reduce handwritten SQL.
6. Complete runnable example: simple product inventory system
7. Supporting exercises and solutions
Exercise: Query students in a specified score range
Requirements: Implementationget_score_in(low, high)Function that returns the fraction in[low, high]The names of the students between, sorted by score from low to high.

