鸿蒙5 本地数据库:@ohos.data.relationalStore 管理用户数据实践指南

暗雨OL
发布于 2025-6-27 21:59
浏览
0收藏

一、鸿蒙关系型数据库概述
@ohos.data.relationalStore 是鸿蒙OS提供的关系型数据库模块,基于SQLite构建,支持完整的关系型数据库特性,包括:

本地数据持久化存储
完整SQL语法支持
事务和连接池管理
数据库加密和跨设备同步
数据订阅变更通知
二、数据库核心操作实现

  1. 数据库初始化与表创建
    // database/UserDBManager.ets
    import relationalStore from ‘@ohos.data.relationalStore’;
    import UIAbility from ‘@ohos.app.ability.UIAbility’;

// 数据库表结构定义
const USER_SCHEMA = {
tableName: ‘users’,
columns: [
{ name: ‘id’, type: relationalStore.StoreType.INTEGER, primaryKey: true, autoIncrement: true },
{ name: ‘name’, type: relationalStore.StoreType.STRING, notNull: true },
{ name: ‘age’, type: relationalStore.StoreType.INTEGER },
{ name: ‘email’, type: relationalStore.StoreType.STRING },
{ name: ‘created_at’, type: relationalStore.StoreType.INTEGER, defaultValue: “STRFTIME(‘%Y-%m-%d %H:%M:%f’, ‘NOW’)” },
{ name: ‘updated_at’, type: relationalStore.StoreType.INTEGER }
],
indexes: [
{ name: ‘email_index’, fields: [‘email’], unique: true }
]
};

const DB_NAME = ‘user_data.db’;
const DB_VERSION = 1;

export class UserDBManager {
private static rdbStore: relationalStore.RdbStore | null = null;

// 初始化数据库
static async initialize(context: UIAbility.Context) {
if (!this.rdbStore) {
const config: relationalStore.StoreConfig = {
name: DB_NAME,
securityLevel: relationalStore.SecurityLevel.S1, // 数据库安全级别
encrypted: true // 数据库加密
};

  try {
    // 创建或打开数据库
    this.rdbStore = await relationalStore.getRdbStore(context, config);
    console.info('Database opened successfully.');
    
    // 创建用户表
    await this.createTable();
  } catch (err) {
    console.error(`Failed to initialize database: ${JSON.stringify(err)}`);
  }
}
return this.rdbStore;
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.

}

// 创建用户表
private static async createTable() {
if (!this.rdbStore) return;

// 检查表是否存在
const tableExists = await this.checkTableExists();
if (!tableExists) {
  try {
    await this.rdbStore.executeSql(
      `CREATE TABLE IF NOT EXISTS ${USER_SCHEMA.tableName} (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        name TEXT NOT NULL,
        age INTEGER,
        email TEXT,
        created_at INTEGER DEFAULT (strftime('%s','now')),
        updated_at INTEGER
      );`
    );
    
    // 创建索引
    await this.rdbStore.executeSql(
      `CREATE UNIQUE INDEX IF NOT EXISTS email_index ON ${USER_SCHEMA.tableName}(email);`
    );
    
    console.info('User table created successfully.');
  } catch (err) {
    console.error(`Failed to create table: ${JSON.stringify(err)}`);
  }
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.

}

// 检查表是否存在
private static async checkTableExists(): Promise<boolean> {
if (!this.rdbStore) return false;

try {
  const result = await this.rdbStore.querySql(
    `SELECT name FROM sqlite_master WHERE type='table' AND name=?;`,
    [USER_SCHEMA.tableName]
  );
  
  return result.length > 0;
} catch (err) {
  console.error(`Error checking table existence: ${JSON.stringify(err)}`);
  return false;
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.

}

// 获取数据库实例
static getStore(): relationalStore.RdbStore | null {
return this.rdbStore;
}
}
2. 数据模型定义
// models/User.ts
export class User {
id?: number; // 主键,自增ID
name: string; // 用户姓名
age?: number; // 用户年龄
email?: string; // 用户邮箱
createdAt?: number; // 创建时间戳
updatedAt?: number; // 更新时间戳

constructor(name: string, age?: number, email?: string) {
this.name = name;
this.age = age;
this.email = email;
this.createdAt = Math.floor(Date.now() / 1000);
this.updatedAt = Math.floor(Date.now() / 1000);
}

// 从结果集构建User对象
static fromResultSet(resultSet: relationalStore.ResultSet): User {
const user = new User(‘’);
user.id = resultSet.getDouble(resultSet.getColumnIndex(‘id’));
user.name = resultSet.getString(resultSet.getColumnIndex(‘name’));
user.age = resultSet.getDouble(resultSet.getColumnIndex(‘age’));
user.email = resultSet.getString(resultSet.getColumnIndex(‘email’));
user.createdAt = resultSet.getDouble(resultSet.getColumnIndex(‘created_at’));
user.updatedAt = resultSet.getDouble(resultSet.getColumnIndex(‘updated_at’));
return user;
}
}
三、CRUD操作实现

  1. 添加用户
    // database/UserDao.ets
    import { User } from ‘…/models/User’;
    import relationalStore from ‘@ohos.data.relationalStore’;

export class UserDao {
// 插入用户数据
static async addUser(user: User): Promise<number> {
const rdbStore = UserDBManager.getStore();
if (!rdbStore) throw new Error(‘Database not initialized’);

const valueBucket: relationalStore.ValuesBucket = {
  'name': user.name,
  'age': user.age,
  'email': user.email,
  'created_at': user.createdAt,
  'updated_at': user.updatedAt
};

try {
  const rowId = await rdbStore.insert('users', valueBucket);
  console.info(`User added with row ID: ${rowId}`);
  return rowId;
} catch (err) {
  console.error(`Failed to add user: ${JSON.stringify(err)}`);
  throw err;
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.

}

// 批量插入用户
static async batchAddUsers(users: User[]): Promise<number> {
const rdbStore = UserDBManager.getStore();
if (!rdbStore) throw new Error(‘Database not initialized’);

try {
  await rdbStore.beginTransaction();
  
  let successCount = 0;
  for (const user of users) {
    const valueBucket: relationalStore.ValuesBucket = {
      'name': user.name,
      'age': user.age,
      'email': user.email,
      'created_at': user.createdAt,
      'updated_at': user.updatedAt
    };
    
    await rdbStore.insert('users', valueBucket);
    successCount++;
  }
  
  await rdbStore.commit();
  return successCount;
} catch (err) {
  await rdbStore.rollback();
  console.error(`Failed to batch add users: ${JSON.stringify(err)}`);
  throw err;
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.

}
}
2. 查询用户数据
// 在 UserDao 类中添加

// 根据ID查询用户
static async getUserById(id: number): Promise<User | null> {
const rdbStore = UserDBManager.getStore();
if (!rdbStore) throw new Error(‘Database not initialized’);

const predicates = new relationalStore.RdbPredicates(‘users’);
predicates.equalTo(‘id’, id);

try {
const result = await rdbStore.query(predicates, [‘id’, ‘name’, ‘age’, ‘email’, ‘created_at’, ‘updated_at’]);
if (result.rowCount === 0) return null;

result.goToFirstRow();
const user = User.fromResultSet(result);
result.close();

return user;
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.

} catch (err) {
console.error(Failed to get user by ID: ${JSON.stringify(err)});
throw err;
}
}

// 查询所有用户
static async getAllUsers(): Promise<User[]> {
const rdbStore = UserDBManager.getStore();
if (!rdbStore) throw new Error(‘Database not initialized’);

const predicates = new relationalStore.RdbPredicates(‘users’);

try {
const result = await rdbStore.query(predicates, [‘id’, ‘name’, ‘age’, ‘email’, ‘created_at’, ‘updated_at’]);
const users: User[] = [];

while (!result.isEnded) {
  users.push(User.fromResultSet(result));
  result.goToNextRow();
}

result.close();
return users;
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.

} catch (err) {
console.error(Failed to get all users: ${JSON.stringify(err)});
throw err;
}
}

// 条件查询(示例:按年龄范围查询)
static async getUsersByAgeRange(minAge: number, maxAge: number): Promise<User[]> {
const rdbStore = UserDBManager.getStore();
if (!rdbStore) throw new Error(‘Database not initialized’);

const predicates = new relationalStore.RdbPredicates(‘users’);
predicates.greaterThanOrEqualTo(‘age’, minAge)
.and()
.lessThanOrEqualTo(‘age’, maxAge)
.orderByDesc(‘age’); // 按年龄降序排列

try {
const result = await rdbStore.query(predicates, [‘id’, ‘name’, ‘age’, ‘email’, ‘created_at’, ‘updated_at’]);
const users: User[] = [];

while (!result.isEnded) {
  users.push(User.fromResultSet(result));
  result.goToNextRow();
}

result.close();
return users;
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.

} catch (err) {
console.error(Failed to get users by age: ${JSON.stringify(err)});
throw err;
}
}
3. 更新用户数据
// 在 UserDao 类中添加

// 更新用户信息
static async updateUser(user: User): Promise<number> {
const rdbStore = UserDBManager.getStore();
if (!rdbStore) throw new Error(‘Database not initialized’);

const valueBucket: relationalStore.ValuesBucket = {
‘name’: user.name,
‘age’: user.age,
‘email’: user.email,
‘updated_at’: Math.floor(Date.now() / 1000)
};

const predicates = new relationalStore.RdbPredicates(‘users’);
predicates.equalTo(‘id’, user.id);

try {
const rowsUpdated = await rdbStore.update(valueBucket, predicates);
console.info(User ${user.id} updated, affected rows: ${rowsUpdated});
return rowsUpdated;
} catch (err) {
console.error(Failed to update user: ${JSON.stringify(err)});
throw err;
}
}
4. 删除用户数据
// 在 UserDao 类中添加

// 根据ID删除用户
static async deleteUserById(id: number): Promise<number> {
const rdbStore = UserDBManager.getStore();
if (!rdbStore) throw new Error(‘Database not initialized’);

const predicates = new relationalStore.RdbPredicates(‘users’);
predicates.equalTo(‘id’, id);

try {
const rowsDeleted = await rdbStore.delete(predicates);
console.info(User ${id} deleted, affected rows: ${rowsDeleted});
return rowsDeleted;
} catch (err) {
console.error(Failed to delete user: ${JSON.stringify(err)});
throw err;
}
}

// 根据条件删除用户
static async deleteUsersByAge(minAge: number): Promise<number> {
const rdbStore = UserDBManager.getStore();
if (!rdbStore) throw new Error(‘Database not initialized’);

const predicates = new relationalStore.RdbPredicates(‘users’);
predicates.greaterThanOrEqualTo(‘age’, minAge);

try {
const rowsDeleted = await rdbStore.delete(predicates);
console.info(Users older than ${minAge} deleted, count: ${rowsDeleted});
return rowsDeleted;
} catch (err) {
console.error(Failed to delete users by age: ${JSON.stringify(err)});
throw err;
}
}
四、高级数据库功能实现

  1. 数据库升级与迁移
    // 在 UserDBManager 类中添加

// 数据库升级处理
static async handleUpgrade(oldVersion: number, newVersion: number) {
const rdbStore = this.rdbStore;
if (!rdbStore) return;

try {
// 版本2升级:添加用户类型字段
if (oldVersion < 2 && newVersion >= 2) {
await rdbStore.executeSql(
‘ALTER TABLE users ADD COLUMN type TEXT DEFAULT “normal”;’
);
console.info(‘Database upgraded to version 2’);
}

// 版本3升级:添加用户状态字段
if (oldVersion < 3 && newVersion >= 3) {
  await rdbStore.executeSql(
    'ALTER TABLE users ADD COLUMN status INTEGER DEFAULT 1;'
  );
  console.info('Database upgraded to version 3');
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.

} catch (err) {
console.error(Failed to upgrade database: ${JSON.stringify(err)});
}
}
2. 数据加密与安全
// 配置数据库加密密钥
const initEncryptedDatabase = async () => {
try {
const config: relationalStore.StoreConfig = {
name: ‘secure_data.db’,
securityLevel: relationalStore.SecurityLevel.S4, // 最高安全级别
encrypted: true
};

// 设置加密密钥(第一次初始化)
await relationalStore.createRdbStore(context, config, (store) => {
  store.setVersion(1);
  store.executeSql('CREATE TABLE ...');
}, 'MyStrongPassword123!');

// 打开已加密数据库
const rdbStore = await relationalStore.getRdbStore(context, config, 'MyStrongPassword123!');
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.

} catch (err) {
console.error(‘Encrypted database error:’, JSON.stringify(err));
}
};
3. 订阅数据变更通知
// 订阅数据库变更
static subscribeToUserChanges(callback: (event: relationalStore.SubscribeEvent) => void): number | undefined {
const rdbStore = UserDBManager.getStore();
if (!rdbStore) return;

const observer = (event: relationalStore.SubscribeEvent) => {
console.info(Data change event: ${JSON.stringify(event)});
callback(event);
};

return rdbStore.subscribe(relationalStore.SubscribeType.SUBSCRIBE_TYPE_REMOTE, observer);
}

// 取消订阅
static unsubscribe(subId: number) {
const rdbStore = UserDBManager.getStore();
if (!rdbStore) return;

rdbStore.unsubscribe(subId);
}
4. 使用原生SQL执行复杂查询
// 执行原生SQL查询
static async rawQuery(sql: string, params: any[] = []): Promise<any[]> {
const rdbStore = UserDBManager.getStore();
if (!rdbStore) throw new Error(‘Database not initialized’);

try {
const result = await rdbStore.querySql(sql, params);
const data: any[] = [];

while (!result.isEnded) {
  const row: Record<string, any> = {};
  for (let i = 0; i < result.columnCount; i++) {
    const colName = result.getColumnName(i);
    const colType = result.getDataType(i);
    
    switch (colType) {
      case relationalStore.DataType.TYPE_INTEGER:
        row[colName] = result.getInt(i);
        break;
      case relationalStore.DataType.TYPE_FLOAT:
        row[colName] = result.getDouble(i);
        break;
      case relationalStore.DataType.TYPE_STRING:
        row[colName] = result.getString(i);
        break;
      case relationalStore.DataType.TYPE_BLOB:
        row[colName] = result.getBlob(i);
        break;
      default:
        row[colName] = result.getString(i);
    }
  }
  data.push(row);
  result.goToNextRow();
}

result.close();
return data;
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.

} catch (err) {
console.error(Raw query failed: ${JSON.stringify(err)});
throw err;
}
}
五、数据库在UI中的完整应用

  1. 用户列表页面实现
    // pages/UserListPage.ets
    import { User } from ‘…/models/User’;
    import { UserDao } from ‘…/database/UserDao’;

@Entry
@Component
struct UserListPage {
@State users: User[] = [];

aboutToAppear() {
this.loadUsers();
}

async loadUsers() {
try {
this.users = await UserDao.getAllUsers();
} catch (err) {
console.error(‘Failed to load users:’, JSON.stringify(err));
}
}

build() {
Column() {
// 标题
Text(‘用户列表’)
.fontSize(24)
.fontWeight(FontWeight.Bold)
.margin({ top: 24, bottom: 20 })

  // 用户列表
  List() {
    ForEach(this.users, (user) => {
      ListItem() {
        this.userItem(user)
      }
      .onClick(() => {
        // 导航到用户详情页
        router.pushUrl({ url: 'pages/UserDetailPage', params: { userId: user.id } });
      })
    }, user => user.id ? user.id.toString() : '')
  }
  .divider({ strokeWidth: 1, color: '#EEE', startMargin: 16, endMargin: 16 })
  .layoutWeight(1)
  
  // 添加按钮
  Button('添加用户', { type: ButtonType.Capsule })
    .width('80%')
    .height(50)
    .margin(20)
    .onClick(() => {
      router.pushUrl({ url: 'pages/AddUserPage' });
    })
}
.padding(16)
.width('100%')
.height('100%')
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.

}

@Builder
userItem(user: User) {
Row() {
Column() {
Text(user.name)
.fontSize(18)
.fontWeight(FontWeight.Medium)

    Text(`年龄: ${user.age || '未设置'}`)
      .fontSize(14)
      .opacity(0.8)
      .margin({ top: 6 })
  }
  .layoutWeight(1)
  
  Image($r('app.media.ic_arrow_right'))
    .width(24)
    .height(24)
}
.padding(16)
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.

}
}
2. 添加用户页面
// pages/AddUserPage.ets
import { User } from ‘…/models/User’;
import { UserDao } from ‘…/database/UserDao’;

@Entry
@Component
struct AddUserPage {
@State name: string = ‘’;
@State age: string = ‘’;
@State email: string = ‘’;

private async addUser() {
if (!this.name.trim()) {
AlertDialog.show({ message: ‘请输入姓名’ });
return;
}

const newUser = new User(
  this.name.trim(),
  this.age ? parseInt(this.age) : undefined,
  this.email ? this.email.trim() : undefined
);

try {
  const newId = await UserDao.addUser(newUser);
  console.info(`User created with ID: ${newId}`);
  
  // 返回上一页
  router.back();
} catch (err) {
  const errorMsg = (err as any)?.code === 1 ? '邮箱地址已存在' : '添加失败';
  AlertDialog.show({ message: errorMsg });
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.

}

build() {
Column() {
Text(‘添加新用户’)
.fontSize(24)
.fontWeight(FontWeight.Bold)
.margin({ top: 24, bottom: 20 })

  // 姓名输入
  TextInput({ placeholder: '姓名(必填)', text: this.name })
    .onChange(val => this.name = val)
    .margin({ bottom: 12 })
  
  // 年龄输入
  TextInput({ placeholder: '年龄', text: this.age })
    .onChange(val => this.age = val)
    .keyboardType(InputType.Number)
    .margin({ bottom: 12 })
  
  // 邮箱输入
  TextInput({ placeholder: '邮箱', text: this.email })
    .onChange(val => this.email = val)
    .keyboardType(InputType.Email)
    .margin({ bottom: 24 })
  
  // 提交按钮
  Button('保存', { type: ButtonType.Capsule })
    .width('100%')
    .height(50)
    .onClick(() => this.addUser())
  
}
.padding(24)
.height('100%')
.backgroundColor('#FFFFFF')
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.

}
}
六、性能优化与最佳实践

  1. 批量操作优化
    // 批量更新用户年龄
    static async batchUpdateUserAges(ageMap: Map<number, number>): Promise<number> {
    const rdbStore = UserDBManager.getStore();
    if (!rdbStore) throw new Error(‘Database not initialized’);

try {
await rdbStore.beginTransaction();

let updateCount = 0;
for (const [userId, newAge] of ageMap.entries()) {
  const valueBucket: relationalStore.ValuesBucket = {
    'age': newAge,
    'updated_at': Math.floor(Date.now() / 1000)
  };
  
  const predicates = new relationalStore.RdbPredicates('users');
  predicates.equalTo('id', userId);
  
  const rowsAffected = await rdbStore.update(valueBucket, predicates);
  if (rowsAffected > 0) updateCount++;
}

await rdbStore.commit();
return updateCount;
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.

} catch (err) {
await rdbStore.rollback();
console.error(Batch update failed: ${JSON.stringify(err)});
throw err;
}
}
2. 索引优化查询
// 添加索引
static async optimizeQueries() {
const rdbStore = UserDBManager.getStore();
if (!rdbStore) return;

try {
// 为查询字段创建索引
await rdbStore.executeSql(‘CREATE INDEX IF NOT EXISTS name_idx ON users(name);’);

// 为联合查询创建索引
await rdbStore.executeSql('CREATE INDEX IF NOT EXISTS name_age_idx ON users(name, age);');

console.info('Database indexes created.');
  • 1.
  • 2.
  • 3.
  • 4.

} catch (err) {
console.error(Index creation failed: ${JSON.stringify(err)});
}
}
3. 分页查询实现
// 分页查询用户
static async getUsersPaginated(page: number, pageSize: number): Promise<User[]> {
const rdbStore = UserDBManager.getStore();
if (!rdbStore) throw new Error(‘Database not initialized’);

const offset = (page - 1) * pageSize;

const predicates = new relationalStore.RdbPredicates(‘users’);
predicates.orderByAsc(‘id’).offset(offset).limit(pageSize);

try {
const result = await rdbStore.query(predicates);
const users: User[] = [];

while (!result.isEnded) {
  users.push(User.fromResultSet(result));
  result.goToNextRow();
}

result.close();
return users;
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.

} catch (err) {
console.error(Pagination query failed: ${JSON.stringify(err)});
throw err;
}
}
七、常见问题解决

  1. 数据库锁定问题
    // 数据库重试机制
    static async executeWithRetry<T>(operation: () => Promise<T>, maxRetries = 3): Promise<T> {
    let retries = 0;

while (retries < maxRetries) {
try {
return await operation();
} catch (err) {
if (err.code === relationalStore.BUSY_CONSTRAINT) {
retries++;
console.warn(Database busy, retrying (${retries}/${maxRetries}));
await new Promise(resolve => setTimeout(resolve, 50 * retries)); // 指数退避
} else {
throw err;
}
}
}

throw new Error(‘Database operation failed after retries’);
}
2. 数据库升级失败处理
// 数据库恢复机制
static async recoverDatabase(context: UIAbility.Context) {
const dbPath = context.filesDir + /${DB_NAME};

try {
// 1. 备份当前数据库
const backupPath = context.filesDir + /${DB_NAME}.bak;
await fileIO.copyFile(dbPath, backupPath);

// 2. 删除损坏数据库
await fileIO.unlink(dbPath);

// 3. 重新初始化数据库
await UserDBManager.initialize(context);

console.warn('Database recovered successfully');
return true;
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.

} catch (err) {
console.error(‘Database recovery failed:’, JSON.stringify(err));
return false;
}
}
八、总结
鸿蒙OS的 @ohos.data.relationalStore 模块提供了强大的本地数据管理能力,通过本文的实现方案,你可以:

创建安全的关系型数据库
实现完整的CRUD操作
处理数据库版本迁移
优化数据库性能
在UI中展示和管理数据
在开发过程中,注意以下几点可获得最佳实践:

​​始终使用异步操作​​:避免阻塞UI主线程
​​妥善管理事务​​:确保复杂操作的原子性
​​合理设计数据模型​​:提前规划数据库结构
​​实现错误恢复机制​​:增强应用健壮性
​​加密敏感数据​​:保护用户隐私
本文提供的代码可直接集成到鸿蒙应用中,结合具体业务需求调整数据模型和操作逻辑,构建出高效可靠的数据持久化解决方案。

分类
标签
收藏
回复
举报


回复
    相关推荐
    恭喜您,今日已阅读两篇内容,特奖励+2声望, 快来领取吧。