关注

华为deveco里使用数据库SQLite

2025-2-22华为社区评论:

可知SQLite的版本是HarmonyOS系统内置好的, 有封装好的RDB接口

实现简单的登录注册:

路径设置为:

可以这样写,我用的是13版本api

import relationalStore from '@ohos.data.relationalStore';

// 定义数据库配置接口
interface StoreConfig {
  name: string;
  securityLevel: relationalStore.SecurityLevel;
}

// 定义用户数据接口
interface UserData {
  username: string;
  password: string;
  phone: string;
}

export class Rdb {
  private rdbStore: relationalStore.RdbStore | null = null;
  private readonly tableName: string = 'USER_TABLE';
  private readonly sqlCreateTable: string = 'CREATE TABLE IF NOT EXISTS USER_TABLE (id INTEGER PRIMARY KEY AUTOINCREMENT, username TEXT NOT NULL, password TEXT NOT NULL, phone TEXT NOT NULL)';

  constructor(callback: () => void = () => {}) {
    this.getRdbStore(() => {
      this.createTable(() => {
        callback();
      });
    });
  }

  public getRdbStore(callback: () => void = () => {}): void {
    if (this.rdbStore !== null) {
      callback();
      return;
    }

    const config: StoreConfig = {
      name: 'user.db',
      securityLevel: relationalStore.SecurityLevel.S1
    };

    relationalStore.getRdbStore(getContext(this), config, (err, store) => {
      if (err) {
        console.error(`Failed to get RdbStore, code is ${err.code}, message is ${err.message}`);
        return;
      }
      this.rdbStore = store;
      callback();
    });
  }

  private createTable(callback: () => void = () => {}): void {
    if (this.rdbStore === null) {
      console.error('RdbStore is not ready');
      return;
    }
    this.rdbStore.executeSql(this.sqlCreateTable);
    callback();
  }

  // 插入用户数据
  public insertData(user: UserData, callback: (success: boolean) => void): void {
    if (this.rdbStore === null) {
      console.error('RdbStore is not ready');
      callback(false);
      return;
    }

    const valueBucket: relationalStore.ValuesBucket = {
      'username': user.username,
      'password': user.password,
      'phone': user.phone
    };

    this.rdbStore.insert(this.tableName, valueBucket, (err, rowId) => {
      if (err) {
        console.error(`Failed to insert data, code is ${err.code}, message is ${err.message}`);
        callback(false);
        return;
      }
      console.info(`Succeeded in inserting data, rowId = ${rowId}`);
      callback(true);
    });
  }

  // 查询用户
  public queryUser(username: string, password: string, callback: (success: boolean) => void): void {
    if (this.rdbStore === null) {
      console.error('RdbStore is not ready');
      callback(false);
      return;
    }

    const predicates = new relationalStore.RdbPredicates(this.tableName);
    predicates.equalTo('username', username).and().equalTo('password', password);

    this.rdbStore.query(predicates, ['id', 'username', 'password', 'phone'], (err, resultSet) => {
      if (err) {
        console.error(`Failed to query data, code is ${err.code}, message is ${err.message}`);
        callback(false);
        return;
      }
      callback(resultSet.rowCount > 0);
      resultSet.close();
    });
  }

  // 检查用户名是否存在
  public checkUsername(username: string, callback: (exists: boolean) => void): void {
    if (this.rdbStore === null) {
      console.error('RdbStore is not ready');
      callback(false);
      return;
    }

    const predicates = new relationalStore.RdbPredicates(this.tableName);
    predicates.equalTo('username', username);

    this.rdbStore.query(predicates, ['username'], (err, resultSet) => {
      if (err) {
        console.error(`Failed to query data, code is ${err.code}, message is ${err.message}`);
        callback(false);
        return;
      }
      callback(resultSet.rowCount > 0);
      resultSet.close();
    });
  }
}

export default new Rdb(); 

这里实现登录逻辑和注册逻辑

import router from '@ohos.router';
import promptAction from '@ohos.promptAction';
import Rdb from '../common/database/Rdb';

@Entry
@Component
struct LoginPage {
  @State username: string = '';
  @State password: string = '';

  build() {
    // ... UI代码...

    Button("登录")
      .width(350)
      .height(50)
      .margin({ top: 30 })
      .onClick(() => {
        if (!this.username || !this.password) {
          promptAction.showToast({ message: '请输入用户名和密码' });
          return;
        }
        // 验证登录
        Rdb.queryUser(this.username, this.password, (success: boolean) => {
          if (success) {
            promptAction.showToast({ message: '登录成功' });
            router.pushUrl({ url: 'pages/MainPage' });
          } else {
            promptAction.showToast({ message: '用户名或密码错误' });
          }
        });
      })

  }
}
import router from '@ohos.router';
import promptAction from '@ohos.promptAction';
import Rdb from '../common/database/Rdb';

@Entry
@Component
struct LoginPage {
  // ... 其他状态代码保持不变 ...

  build() {
    // ...UI代码 ...

    Button("注册")
      .width(350)
      .height(50)
      .margin({ top: 30 })
      .onClick(() => {
        // 验证逻辑
        if (!this.username || !this.password || !this.confirmPassword || !this.phone) {
          promptAction.showToast({ message: '请填写完整信息' });
          return;
        }
        if (!/^1[3-9]\d{9}$/.test(this.phone)) {
          promptAction.showToast({ message: '请输入正确的手机号' });
          return;
        }
        if (this.password !== this.confirmPassword) {
          promptAction.showToast({ message: '两次密码不一致' });
          return;
        }

        // 检查用户名是否已存在
        Rdb.checkUsername(this.username, (exists: boolean) => {
          if (exists) {
            promptAction.showToast({ message: '用户名已存在' });
            return;
          }

          // 注册新用户
          Rdb.insertData({
            username: this.username,
            password: this.password,
            phone: this.phone
          }, (success: boolean) => {
            if (success) {
              promptAction.showToast({ message: '注册成功' });
              router.pushUrl({ url: 'pages/LoginPage' });
            } else {
              promptAction.showToast({ message: '注册失败,请重试' });
            }
          });
        });
      })

  }
}

转载自CSDN-专业IT技术社区

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。

原文链接:https://blog.csdn.net/2301_77725709/article/details/145878430

评论

赞0

评论列表

微信小程序
QQ小程序

关于作者

点赞数:0
关注数:0
粉丝:0
文章:0
关注标签:0
加入于:--