数据层
数据层 · androidx.room3
SQLite:Room3 之下的直接 APIRoom3 3.0.0-rc01
只有需要自行管理 SQL、连接和事务时才下沉到 SQLite 层。
最后更新 2026-08-01
复制即用
import androidx.sqlite.SQLiteConnection
import androidx.sqlite.SQLiteDriver
import androidx.sqlite.driver.AndroidSQLiteDriver
val driver: SQLiteDriver = AndroidSQLiteDriver()
// 打开连接
val connection: SQLiteConnection = driver.open("notes.db")
// 执行 DDL / 无参数语句
connection.prepare("CREATE TABLE IF NOT EXISTS note (id INTEGER PRIMARY KEY, title TEXT)")
.close()
// 参数化查询
val statement = connection.prepare("INSERT INTO note(title) VALUES(?)")
statement.bindText(1, "购物清单")
statement.step()
statement.close()
// 查询并读结果
val query = connection.prepare("SELECT id, title FROM note")
while (query.step()) {
val id = query.getLong(0) // 0-based 列索引
val title = query.getText(1)
}
query.close()
connection.close()核心类型
| 类型 | 职责 |
|---|---|
SQLiteDriver | 打开数据库文件的入口(open(fileName)) |
AndroidSQLiteDriver | Android 实现,内部走 SQLiteDatabase,hasConnectionPool = true |
SQLiteConnection | 单连接:prepare(sql)、inTransaction()、close() |
SQLiteStatement | 预编译语句:bind*(1-based 参数)、get*(0-based 列)、step() |
绑定/读取速查:
statement.bindText(1, "文本") // bindLong/bindDouble/bindBlob/bindNull
statement.step() // 有行返回 true;无行 false
statement.getLong(0) // getText/getDouble/getBlob/isNull驱动模块
| 模块 | 平台 |
|---|---|
sqlite-framework | Android(AndroidSQLiteDriver) |
sqlite-bundled | 多平台(自带 SQLite 引擎) |
sqlite-ktx | Kotlin 扩展(Flow、协程等) |
职责边界
无论用哪层,都要明确:
- 事务边界由哪一层拥有。
- statement/connection 何时关闭或归还。
- schema version 与 migration 如何测试。
- 查询在哪个 dispatcher/连接上下文运行。
Room3 对比
| 场景 | Room3 | SQLite 直连 |
|---|---|---|
| Entity/DAO 生成 | 有(编译期校验) | 无 |
| schema 迁移策略 | 内置 | 自己管理 |
| SQL 映射 | 自动 | 手写 |
| 适合 | 普通应用 CRUD | 框架作者、大型手写 SQL 层、Room 未暴露的底层能力 |
常见陷阱
- 忘关闭:statement 和 connection 都持有资源,用完
close()。 - 多线程共享连接:
AndroidSQLiteDriver有连接池,但无池的驱动要自己管理线程安全。 - Room 和 SQLite 直连混用:不要同时让 Room 和另一套连接管理器对同一个文件各自猜测事务状态。
- bind 索引从 1 开始,get 从 0 开始:混错索引直接报错或读到错误列。
要点
androidx.sqlite:sqlite:2.7.0-rc01定义跨平台 SQLite API;驱动模块负责真正打开数据库。它不提供 Entity、DAO 生成或 schema 迁移策略。- 适合直接使用 SQLite 的场景包括:数据库框架作者、已有大型手写 SQL 层、需要 Room 未暴露的底层能力。普通应用 CRUD 优先 Room3,因为 SQL 映射和 schema 验证能在编译期发现更多错误。
- 事务边界、连接关闭、schema 迁移、查询 dispatcher 都由调用方负责。