关于Rdb的介绍可以自行查看官方文档:关系型数据库,我这里只给出RDB的基本用法(插入、更新、查找)。工具类完整代码在文末。

目录

1. 导入模块

2.创建工具类  RdbUtil,并实现getRdbStore方法。

3. 创建或打开已有的关系型数据库

4.  在工具类 RdbUtil 中,实现insert()方法:向表中插入数据。

5. 在页面中调用工具类中的 insert 方法,实现插入数据逻辑。

6.  在工具类 RdbUtil 中,实现Login()方法:查询数据。

完整代码


下面是实现步骤:

1. 导入模块

import { relationalStore } from '@kit.ArkData';

2.创建工具类  RdbUtil,并实现getRdbStore方法。

import { relationalStore } from '@kit.ArkData';
import { BusinessError } from '@kit.BasicServicesKit';
import { promptAction } from '@kit.ArkUI';

/**
 * 关系型数据库 RDB
 */

class RdbUtil {

  /* 用来调用RDB方法 */
  private store: relationalStore.RdbStore | undefined = undefined;
  /* 表名 */
  private table: string = "user";

  /**
   * 数据库配置项
   * name: 数据库文件名
   * securityLevel: 数据库安全级别
   * 具体参数可参考:https://developer.huawei.com/consumer/cn/doc/harmonyos-references/js-apis-data-relationalstore#storeconfig 
   */
  private STORE_CONFIG: relationalStore.StoreConfig = {
    name: "News.db",
    securityLevel: relationalStore.SecurityLevel.S3
  };

  /**
   * sql 建表语句
   */
  private createTableSql: string = `
      CREATE TABLE IF NOT EXISTS ${this.table} (
        id INT AUTO_INCREMENT,           -- 自增长的主键字段
        account VARCHAR(20) NOT NULL,    -- 账号(手机号码),最大长度 20
        password VARCHAR(255) NOT NULL,  -- 密码,最大长度 255
        nickname VARCHAR(255),           -- 昵称,最大长度 255, 默认昵称为账号
        PRIMARY KEY (id)                 -- 设置 id 为主键
       );`;


  /**
   * 创建、打开已有的关系型数据库
   * @param context
   */
  getRdbStore(context: Context) {
    relationalStore.getRdbStore(context, this.STORE_CONFIG, async (err: BusinessError, rdbStore: relationalStore.RdbStore) => {
      if (err) {
        console.error(`RdbStore 获取失败, 状态码: ${err.code}, 返回信息: ${err.message}`);
        return;
      }
      console.log('RdbStore 获取成功');
      this.store = rdbStore;
      // 初始化数据库表结构和相关数据
      this.store.executeSql(this.createTableSql);
    });
  }
}
/* 单例模式 */
const myRdbUtil: RdbUtil = new RdbUtil();
export default myRdbUtil;

3. 创建或打开已有的关系型数据库

在src/main/ets/entryability/EntryAbility.ets文件下的onWindowStageCreate()方法中调用我们刚才工具类中的getRdbStore()方法来获取RdbStore对象。

onWindowStageCreate(windowStage: window.WindowStage): void {
    // Main window is created, set main page for this ability
    hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onWindowStageCreate');

    AppStorage.setOrCreate("windowStage",windowStage);

    /* 获取当前app下的RdbStore */
    myRdbUtil.getRdbStore(this.context);

    windowStage.loadContent('pages/LoginPage', (err) => {
      if (err.code) {
        hilog.error(0x0000, 'testTag', 'Failed to load the content. Cause: %{public}s', JSON.stringify(err) ?? '');
        return;
      }
      hilog.info(0x0000, 'testTag', 'Succeeded in loading the content.');
    });
}

4.  在工具类 RdbUtil 中,实现insert()方法:向表中插入数据。

 insert()用法参考:insert()用法

/**
 * 插入用户信息
 * @params: 要插入的数据
 * @return ture: 插入成功
 */
async insert(ac: string, pw: string, nick: string): Promise<boolean> {
  try {
    if (this.store == null) {
      console.error("insert -- RdbStore 未获取")
      return false;
    }

    console.log('RdbStore 插入数据ing……');
    let code: number = await this.store.insert(this.table, {
      id: null,
      account: ac,
      password: pw,
      nickname: nick
    });

    if (code != -1) {
      console.log('RdbStore 插入数据成功 ' + code+"");
      return true;
    }
    return false;
  } catch (e) {
    console.error("RdbStore 插入用户信息报错如下:" + e);
    return false;
  }
}

5. 在页面中调用工具类中的 insert 方法,实现插入数据逻辑。

/** 
  * 注册页面
 */

/* 导入工具类实例 */
import myRdbUtil from '../utils/RdbUtil';
import { promptAction, router } from '@kit.ArkUI';


@Entry
@Component
struct RegisterPage {
   /* ui、字段根据自己需求来,这里ui不是完整的 */

  build() {
    Column() {
      Button("注册")
        .onClick(() => {
          /* 注册事件 */
          myRdbUtil.insert(this.account, this.password, this.account).then((val) => {
            if (val) {
              /* 注册成功回到首页 */
              promptAction.showToast({ message: "注册成功" });
              router.back();
            } else {
              promptAction.showToast({ message: "注册失败" });
    }
  });
        }
      }
  }

}

6.  在工具类 RdbUtil 中,实现Login()方法:查询数据。

 query()用法参考:query()用法

注意:

query需要用到 RdbPredicates 参数,其返回对象为Promise<ResultSet>,ResultSet内置属性方法:ResultSet 参考

RdbPredicates:用来定义数据库的操作条件,参考:RdbPredicates对象及常用谓词

/**
 * 查询指定 account、password
 * @return false: 不存在, true: 已存在
 */
async Login(ac: string, pw: string): Promise<boolean> {
  try {
    if (this.store == null) {
      console.error("insert -- RdbStore 未获取")
      return false;
    }

    console.log("RdbStore 登录ing……" + ac + " " + pw)
    
    /* 创建 RdbPredicates 对象 */
    let predicates = new relationalStore.RdbPredicates(this.table);
    /* 添加谓词条件,下面三行作用:表中找account列值为ac 且 password列值为 pw的数据 */
    predicates.equalTo('account', ac) 
    predicates.and()
    predicates.equalTo('password', pw);
    let res = await this.store.query(predicates, ["account", "password", "nickname"]);

    // 遍历结果
    while (res.goToNextRow()) {
      const name = res.getString(res.getColumnIndex('account'));
      const password = res.getString(res.getColumnIndex('password'));

      console.log(`RdbStore: account: ${name}; password: ${password}`);
    }

    if (res.rowIndex != -1) {
      console.log("RdbStore 登录成功:" + res.rowIndex);
      return true;
    }

    return false;
  } catch (e) {
    console.error("RdbStore 登录报错如下:" + e);
    return false;
  }
}

完整代码

了解上面两种(插入、查找)后,应该可以自行写出编辑、删除。下面是完整代码(我给出了编辑),试着自己出写出删除

import { relationalStore } from '@kit.ArkData';
import { BusinessError } from '@kit.BasicServicesKit';

/**
 * 关系型数据库
 */

class RdbUtil {

  private store: relationalStore.RdbStore | undefined = undefined;
  private table: string = "user";

  /**
   * 数据库配置项
   * name: 数据库文件名
   * securityLevel: 数据库安全级别
   */

  private STORE_CONFIG: relationalStore.StoreConfig = {
    name: "News.db",
    securityLevel: relationalStore.SecurityLevel.S3
  };

  private createTableSql: string = `
      CREATE TABLE IF NOT EXISTS ${this.table} (
        id INT AUTO_INCREMENT,           -- 自增长的主键字段
        account VARCHAR(20) NOT NULL,    -- 账号(手机号码),最大长度 20
        password VARCHAR(255) NOT NULL,  -- 密码,最大长度 255
        nickname VARCHAR(255),           -- 昵称,最大长度 255, 默认昵称为账号
        PRIMARY KEY (id)                -- 设置 id 为主键
       );`;


  /**
   * 创建、打开已有的关系型数据库
   * @param context
   */
  getRdbStore(context: Context) {
    relationalStore.getRdbStore(context, this.STORE_CONFIG, async (err: BusinessError, rdbStore: relationalStore.RdbStore) => {
      if (err) {
        console.error(`RdbStore 获取失败, 状态码: ${err.code}, 返回信息: ${err.message}`);
        return;
      }
      console.log('RdbStore 获取成功');
      this.store = rdbStore;
      // 初始化数据库表结构和相关数据
      this.store.executeSql(this.createTableSql)

    });
  }


  /**
   * 查询指定 account、password
   * @return false: 不存在, true: 已存在
   */
  async Login(ac: string, pw: string): Promise<boolean> {
    try {
      if (this.store == null) {
        console.error("insert -- RdbStore 未获取")
        return false;
      }

      console.log("RdbStore 登录ing……" + ac + " " + pw)

      let predicates = new relationalStore.RdbPredicates(this.table);
      predicates.equalTo('account', ac)
      predicates.and()
      predicates.equalTo('password', pw);
      let res = await this.store.query(predicates, ["account", "password", "nickname"]);

      // 遍历结果
      while (res.goToNextRow()) {
        const name = res.getString(res.getColumnIndex('account'));
        const password = res.getString(res.getColumnIndex('password'));
        console.log(`RdbStore: account: ${name}; password: ${password}`);
      }

      if (res.rowIndex != -1) {
        console.log("RdbStore 登录成功:" + res.rowIndex);
        return true;
      }

      return false;
    } catch (e) {
      console.error("RdbStore 登录报错如下:" + e);
      return false;
    }
  }

  /**
   * 插入用户信息
   */
  async insert(ac: string, pw: string, nick: string): Promise<boolean> {
    try {
      if (this.store == null) {
        console.error("insert -- RdbStore 未获取")
        return false;``
      }

      console.log('RdbStore 插入数据成ing……');
      let code: number = await this.store.insert(this.table, {
        id: null,
        account: ac,
        password: pw,
        nickname: nick
      });

      if (code != -1) {
        console.log('RdbStore 插入数据成功 ' + code+"");
        return true;
      }
      return false;
    } catch (e) {
      console.error("RdbStore 插入用户信息报错如下:" + e);
      return false;
    }

  }


  /**
   * 更新用户信息 可更新:密码、昵称。 账号不可更改。
   * @return true: 更新成功
   */
  async update(ac: string, pw: string, nick: string):Promise<boolean> {
    if (this.store == null) {
      console.error("update -- RdbStore 未获取")
      return false;
    }
    console.log("RdbStore 更新数据ing……", nick);
    try {
      let predicates = new relationalStore.RdbPredicates(this.table);
      predicates.equalTo('account', ac);
      let res = await this.store.update({
        account: ac,
        password: pw,
        nickname: nick
      }, predicates);
      
      // 返回受影响的行数
      if ( res > 0 ) {
        console.log("RdbStore 更新数据成功");
        return true;
      }
      return false;
    } catch (e) {
      console.log("RdbStore 更新数据失败" + e);
    }
    return false;
  }
}
const myRdbUtil: RdbUtil = new RdbUtil();
export default myRdbUtil;

到这里就完结了,希望我的文章对你能有帮助。 

Logo

DAMO开发者矩阵,由阿里巴巴达摩院和中国互联网协会联合发起,致力于探讨最前沿的技术趋势与应用成果,搭建高质量的交流与分享平台,推动技术创新与产业应用链接,围绕“人工智能与新型计算”构建开放共享的开发者生态。

更多推荐