跳转至

第七章:性能优化

索引优化

创建索引

-- 创建索引
CREATE INDEX idx_users_email ON users(email);

-- 创建唯一索引
CREATE UNIQUE INDEX idx_users_name ON users(name);

-- 删除索引
DROP INDEX idx_users_email;

查看查询计划

-- 查看查询计划
EXPLAIN QUERY PLAN SELECT * FROM users WHERE email = 'alice@example.com';

批量操作

批量插入

# 使用 executemany
users = [('Alice', 'alice@example.com'), ('Bob', 'bob@example.com')]
cursor.executemany(
    "INSERT INTO users (name, email) VALUES (?, ?)",
    users
)
conn.commit()

内存数据库

# 内存数据库
conn = sqlite3.connect(':memory:')

# 适合临时数据处理

PRAGMA 优化

-- 设置缓存大小
PRAGMA cache_size = 10000;

-- 设置同步模式
PRAGMA synchronous = NORMAL;

-- 设置日志模式
PRAGMA journal_mode = WAL;

-- 设置临时存储
PRAGMA temp_store = MEMORY;

小结

性能优化要点:

  • 索引优化:CREATE INDEX
  • 批量操作:executemany
  • 内存数据库::memory:
  • PRAGMA 优化:cache_size、synchronous、journal_mode

下一章我们将学习最佳实践。