鸿蒙应用中sqlite数据库存储路径实践
在鸿蒙应用开发过程中,难免会有对本地数据库进行增删改查的需求,正好ArkTs是支持对sqlite数据库进行操作的,如同服务端操作mysql一样。在鸿蒙应用中操作sqlite需要先导入@kit.ArkData模块。示例代码如下:
@Entry
@Component
struct sql_lite_001 {
rdbStore: relationalStore.RdbStore | null = null
DB_NAME = 'my_sql_lite_db_001.db'; // 数据库文件名
STORE_CONFIG: relationalStore.StoreConfig = {
name: this.DB_NAME, // 数据库名称
securityLevel: relationalStore.SecurityLevel.S1 // 安全级别
};
SQL_CREATE_TABLE = `CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
age INTEGER
)`;
aboutToAppear(): void {
this.db_crud()
}
async db_crud() {
await this.onCreate()
}
async onCreate() {
// 初始化数据库
try {
this.rdbStore = await relationalStore.getRdbStore(getContext(), this.STORE_CONFIG);
await this.rdbStore.executeSql(this.SQL_CREATE_TABLE); // 建表
console.log('Database initialized');
} catch (err) {
console.error(`Failed to init DB: ${err.code}, ${err.message}`);
}
}
async onDestroy() {
if (this.rdbStore) {
try {
await this.rdbStore.close();
console.log('Database closed');
} catch (err) {
console.error(`Close DB failed: ${err.code}, ${err.message}`);
}
}
}
build() {
Text('sql lite')
}
}运行上述页面,会建立一个名为my_sql_lite_db_001.db的数据库文件,那么这个文件存储在哪里呢?可以通过console.log(getContext().databaseDir)语句打印出数据库存储的根路径为:/data/storage/el2/database/entry。完整的目录结构如下:
/ ├── chip_prod/ ├── config/ ├── cust/ ├── data/ │ ├── app/ │ │ ├── el1/ │ │ └── el2/ │ └── 100/ │ ├── base/ │ └── database/ │ └── com.example.myapp001/ │ ├── entry/ │ └── rdb/ │ └── lock/ │ ├── my_sql_lite_db_001.db (4KB) │ ├── my_sql_lite_db_001.db-shm (32KB) │ └── my_sql_lite_db_001.db-wal (7.9MB) ├── com.huawei.hmos.arkwebcore/ ├── com.huawei.hmos.calendarData/ └── com.huawei.hmos.filemanager/
可以通过customDir参数指定sqlite数据库文件存储的相对目录,示例代码如下:
// 数据库文件名
DB_NAME = 'my_sql_lite_db_002.db';
STORE_CONFIG: relationalStore.StoreConfig = {
// 数据库名称
name: this.DB_NAME,
// 指定自定义路径:相对路径,相对于应用沙箱目录
customDir: 'custom_db_dir/sqlite_db_dir',
// 安全级别
securityLevel: relationalStore.SecurityLevel.S1
};使用上述customDir:参数指定相对存储路径为'custom_db_dir/sqlite_db_dir'后,实际产生的目录结构如下:
/
├── chip_prod
├── config
├── cust
└── data
└── app
├── el1
└── el2
└── 100
├── base
└── database
└── com.example.myapp001
├── entry
├── rdb
│ └── custom_db_dir
│ └── sqlite_db_dir
│ ├── lock
│ │ ├── my_sqlLite_db_002.db (4KB) (SQLite主数据库文件)
│ │ ├── my_sqlLite_db_002.db-shm (32KB) (SQLite共享内存文件)
│ │ └── my_sqlLite_db_002.db-wal (16.1KB) (SQLite预写日志文件)
├── lock
├── my_sqlLite_db_001.db (4KB) (SQLite主数据库文件)
├── my_sqlLite_db_001.db-shm (32KB) (SQLite共享内存文件)
└── my_sqlLite_db_001.db-wal (7.9MB) (SQLite预写日志文件)
├── com.huawei.hmos.arkwebcore
├── com.huawei.hmos.calendardata
├── com.huawei.hmos.filemanager
└── com.huawei.hmos.files