RDB基础功能使用,适用于基础的代码增删改查和对应的数据备份恢复

适用于基础的代码增删改查和对应的数据备份恢复

HarmonyOS
2024-05-22 23:21:14
浏览
收藏 0
回答 1
待解决
回答 1
按赞同
/
按时间
是潘达不是胖达

relationStore关系型数据库:创建数据库和表;增删改查;数据备份与恢复;启用事务。

import { relationalStore, ValuesBucket } from '@kit.ArkData'; 
 
export default class RdbTest { 
  rdbStore?: relationalStore.RdbStore; 
  context: Context = getContext(this); 
  dataSet?: relationalStore.ResultSet; 
  dbSet: Array<ItemBean> = []; 
 
  MyGetRdbStore() { 
    // SQLite建立 
    interface StoreConfig { 
      name: string; 
      securityLevel: relationalStore.SecurityLevel; 
    } 
 
    const STORE_CONFIG: relationalStore.StoreConfig = { 
      name: 'RdbTest.db', // 数据库文件名 
      securityLevel: relationalStore.SecurityLevel.S1, // 数据库安全级别 
      encrypt: true, // 可选参数,指定数据库是否加密,默认不加密 
      //  dataGroupId: 'dataGroupID' // 可选参数,仅可在Stage模型下使用,表示为应用组ID,需要向应用市场获取。指定在此Id对应的沙箱路径下创建实例,当此参数不填时,默认在本应用沙箱目录下创建。 
    }; 
    relationalStore.getRdbStore(this.context, STORE_CONFIG, (err, store) => { 
      if (err) { 
        console.error(`Failed to get RdbStore. Code:${err.code}, message:${err.message}`); 
        return; 
      } else { 
        console.info(`Succeeded in getting RdbStore.`); 
      } 
      this.rdbStore = store; 
    }) 
  } 
 
  CreateTable() { 
    const SQL_CREATE_TABLE = 'CREATE TABLE IF NOT EXISTS EMPLOYEE (ID INTEGER PRIMARY KEY AUTOINCREMENT,NAME TEXT NOT NULL,AGE INTEGER,SALARY REAL)'; 
    if (this.rdbStore != undefined) { 
      this.rdbStore.executeSql(SQL_CREATE_TABLE); 
    } 
  } 
 
  InsertData(name: string, age: number, salary: number) { 
    // 插入数据 
    const valueBucket: ValuesBucket = { 
      NAME: name, 
      AGE: age, 
      SALARY: salary 
    }; 
    if (this.rdbStore != undefined) { 
      try { 
        //开启事务 
        this.rdbStore.beginTransaction(); 
        this.rdbStore.insert('EMPLOYEE', valueBucket) 
        //提交事务 
        this.rdbStore.commit(); 
        // console.info(`Succeeded in inserting data. rowId:${rowId}`); 
      } 
      catch (err) { 
        //回滚事务 
        this.rdbStore.rollBack() 
        console.error(`Failed to insert data. Code:${err.code}, message:${err.message}`); 
        return; 
      } 
      //回滚事务 
      //this.rdbStore.rollBack() 
      //提交事务 
      console.log("_______________________________________") 
      this.QueryAllData() 
      this.QueryAllData() 
    } 
  } 
 
  UpdateData(updateName: string, name: string, age: number, salary: number) { 
    // 修改数据 
    const valueBucket: ValuesBucket = { 
      NAME: updateName, 
      AGE: age, 
      SALARY: salary 
    }; 
    let predicates = new relationalStore.RdbPredicates('EMPLOYEE'); // 创建表'EMPLOYEE'的predicates 
    predicates.equalTo('NAME', updateName); // 匹配表'EMPLOYEE'中'NAME'为'Lisa'的字段 
    if (this.rdbStore != undefined) { 
      this.rdbStore.update(valueBucket, predicates, (err, rows) => { 
        if (err) { 
          console.error(`Failed to update data. Code:${err.code}, message:${err.message}`); 
          return; 
        } 
        console.info(`Succeeded in updating data. row count: ${rows}`); 
      }) 
    } 
  } 
 
  DeleteData(deleteName: string) { 
    // 删除数据 
    let predicates = new relationalStore.RdbPredicates('EMPLOYEE'); 
    predicates.equalTo('NAME', deleteName); 
    if (this.rdbStore != undefined) { 
      this.rdbStore.delete(predicates, (err, rows) => { 
        if (err) { 
          console.error(`Failed to delete data. Code:${err.code}, message:${err.message}`); 
          return; 
        } 
        console.info(`Delete rows: ${rows}`); 
      }) 
    } 
  } 
 
  UpdateDb(predicates: relationalStore.RdbPredicates) { 
    // 刷新 
    if (this.rdbStore != undefined) { 
      this.rdbStore.query(predicates, ['ID', 'NAME', 'AGE', 'SALARY'], (err, resultSet) => { 
        if (err) { 
          console.error(`Failed to query data. Code:${err.code}, message:${err.message}`); 
          return; 
        } 
        console.info(`ResultSet column names: ${resultSet.columnNames}, column count: ${resultSet.columnCount}`); 
        // resultSet是一个数据集合的游标,默认指向第-1个记录,有效的数据从0开始。 
        this.dbSet = []; 
        while (resultSet.goToNextRow()) { 
          const id = resultSet.getLong(resultSet.getColumnIndex("ID")); 
          const name = resultSet.getString(resultSet.getColumnIndex("NAME")); 
          const age = resultSet.getLong(resultSet.getColumnIndex("AGE")); 
          const salary = resultSet.getDouble(resultSet.getColumnIndex("SALARY")); 
          console.info(`id=${id}, name=${name}, age=${age}, salary=${salary}`); 
          const tmp = new ItemBean(name, age.toString(), salary.toString()); 
          this.dbSet.push(tmp); 
        } 
        // 释放数据集的内存 
        this.dataSet = resultSet; 
        resultSet.close(); 
      }) 
    } 
  } 
 
  QueryAllData() { 
    let predicates = new relationalStore.RdbPredicates('EMPLOYEE'); 
    predicates.inAllDevices(); 
    this.UpdateDb(predicates) 
  } 
 
  QueryData(query: string) { 
    console.log("_______________________________________") 
    let predicates = new relationalStore.RdbPredicates('EMPLOYEE'); 
    predicates.equalTo("NAME", query) 
    this.UpdateDb(predicates) 
    console.log("_______________________________________") 
  } 
 
  backup() { 
    if (this.rdbStore != undefined) { 
      this.rdbStore.backup('dbBackup.db', (err) => { 
        if (err) { 
          console.error(`Failed to backup data. Code:${err.code},message:${err.message}`); 
          return; 
        } 
        console.info(`Succeeded in backuping data.`); 
      }) 
    } 
  } 
 
  //回复数据库 
  restore() { 
    if (this.rdbStore != undefined) { 
      this.rdbStore.restore('dbBackup.db', (err) => { 
        if (err) { 
          console.error(`Failed to restore data. Code:${err.code},message:${err.message}`); 
          return; 
        } 
        console.info(`Succeeded in restoring data.`); 
      }) 
    } 
  } 
}
分享
微博
QQ
微信
回复
2024-05-23 21:06:40
相关问题
如何构建数据库ORM增删改基础能力
1737浏览 • 1回复 待解决
编译适用于HarmonyOS系统openssl
1342浏览 • 1回复 待解决
Pycharm编译器只适用于JAVA吗
8993浏览 • 2回复 待解决
HarmonyOS 开发基础框架
297浏览 • 1回复 待解决