SQLite使用指南
SQLite vs PostgreSQL vs MySQL
| SQLite | PostgreSQL | MySQL | |
|---|---|---|---|
| 适合 | 嵌入式、测试 | 生产Web应用 | Web应用(WordPress) |
| 文件型 | ✓ | ✗ | ✗ |
| 并发写入 | 有限(WAL模式改善) | 出色 | 好 |
| JSON支持 | JSON1 extension | 原生JSONB | JSON type |
SQLite基本命令
-- Create table with best practices
CREATE TABLE users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
email TEXT NOT NULL UNIQUE,
name TEXT NOT NULL,
created INTEGER NOT NULL DEFAULT (unixepoch()),
data TEXT -- JSON stored as text
);
-- Index for common queries
CREATE INDEX idx_users_email ON users(email);
CREATE INDEX idx_users_created ON users(created DESC);
-- Insert with conflict handling
INSERT OR IGNORE INTO users (email, name) VALUES ('a@b.com', 'Alice');
INSERT OR REPLACE INTO users (email, name) VALUES ('a@b.com', 'Alice Updated');
-- JSON operations (JSON1 extension)
SELECT json_extract(data, '$.preferences.theme') FROM users WHERE id=1;
UPDATE users SET data = json_set(data, '$.score', 100) WHERE id=1;
WAL模式(生产环境推荐)
-- Enable WAL mode (persist across connections) PRAGMA journal_mode=WAL; PRAGMA synchronous=NORMAL; -- Faster writes, safe with WAL PRAGMA cache_size=-64000; -- 64MB cache PRAGMA foreign_keys=ON; PRAGMA busy_timeout=5000; -- 5s timeout on lock -- Check current WAL size PRAGMA wal_checkpoint(TRUNCATE);
Go 集成(modernc.org/sqlite纯Go)
import _ "modernc.org/sqlite"
import "database/sql"
db, err := sql.Open("sqlite", "./data.db?_pragma=journal_mode(WAL)")
db.SetMaxOpenConns(1) // SQLite: serialize writes with single conn
db.SetMaxIdleConns(1)