Python SQLite操作
学习sqlite3模块 · 难度:高级 · +15XP
Python SQLite 数据库操作
SQLite 是一个轻量级的嵌入式关系型数据库,它不需要独立的服务器进程,所有数据存储在一个 .db 文件中。Python 标准库中的 sqlite3 模块提供了完整的 SQLite 操作接口。SQLite 非常适合小型应用、移动端开发、本地数据存储和原型开发。
连接数据库与创建表
import sqlite3
# 连接数据库 (如果文件不存在会自动创建)
conn = sqlite3.connect('example.db')
# 创建游标对象
cursor = conn.cursor()
# 创建表
cursor.execute('''
CREATE TABLE IF NOT EXISTS students (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
age INTEGER,
grade REAL DEFAULT 0.0,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
''')
# 提交事务
conn.commit()
增删改查 (CRUD)
import sqlite3
conn = sqlite3.connect('example.db')
cursor = conn.cursor()
# 插入数据 - INSERT
cursor.execute(
'INSERT INTO students (name, age, grade) VALUES (?, ?, ?)',
('小明', 20, 92.5)
)
# 批量插入
students_data = [('小红', 21, 88.0), ('小刚', 19, 95.5)]
cursor.executemany(
'INSERT INTO students (name, age, grade) VALUES (?, ?, ?)',
students_data
)
conn.commit()
# 查询数据 - SELECT
cursor.execute('SELECT * FROM students')
rows = cursor.fetchall()
for row in rows:
print(f'ID: {row[0]}, 姓名: {row[1]}, 年龄: {row[2]}, 成绩: {row[3]}')
# 条件查询
cursor.execute('SELECT * FROM students WHERE grade > ?', (90,))
print(cursor.fetchall())
# 更新数据 - UPDATE
cursor.execute('UPDATE students SET grade = ? WHERE name = ?', (99.0, '小明'))
conn.commit()
# 删除数据 - DELETE
cursor.execute('DELETE FROM students WHERE age < ?', (18,))
conn.commit()
使用上下文管理器
import sqlite3
# 使用 with 语句自动管理事务
with sqlite3.connect('example.db') as conn:
cursor = conn.cursor()
cursor.execute('INSERT INTO students (name, age, grade) VALUES (?, ?, ?)',
('小李', 22, 91.0))
# with 块结束时会自动 commit
# 使用 row_factory 获取字典格式的结果
conn = sqlite3.connect('example.db')
conn.row_factory = sqlite3.Row
cursor = conn.cursor()
cursor.execute('SELECT * FROM students LIMIT 1')
row = cursor.fetchone()
print(dict(row)) # {'id': 1, 'name': '小明', ...}
SQLite 常用 SQL 速查
| 操作 | SQL 语句 |
|---|---|
| 创建表 | CREATE TABLE name (columns...) |
| 插入 | INSERT INTO name VALUES (?, ...) |
| 查询 | SELECT cols FROM name WHERE cond |
| 更新 | UPDATE name SET col=val WHERE cond |
| 删除 | DELETE FROM name WHERE cond |
| 排序 | ORDER BY col ASC/DESC |