开源 Arkts 鸿蒙应用 开发(七)数据持久--sqlite关系数据库

  文章的目的为了记录使用Arkts 进行Harmony app 开发学习的经历。本职为嵌入式软件开发,公司安排开发app,临时学习,完成app的开发。开发流程和要点有些记忆模糊,赶紧记录,防止忘记。

 相关链接:

开源 Arkts 鸿蒙应用 开发(一)工程文件分析-优快云博客

开源 Arkts 鸿蒙应用 开发(二)封装库.har制作和应用-优快云博客

开源 Arkts 鸿蒙应用 开发(三)Arkts的介绍-优快云博客

开源 Arkts 鸿蒙应用 开发(四)布局和常用控件-优快云博客

开源 Arkts 鸿蒙应用 开发(五)控件组成和复杂控件-优快云博客

 推荐链接:

开源 java android app 开发(一)开发环境的搭建-优快云博客

开源 java android app 开发(二)工程文件结构-优快云博客

开源 java android app 开发(三)GUI界面布局和常用组件-优快云博客

开源 java android app 开发(四)GUI界面重要组件-优快云博客

开源 java android app 开发(五)文件和数据库存储-优快云博客

开源 java android app 开发(六)多媒体使用-优快云博客

开源 java android app 开发(七)通讯之Tcp和Http-优快云博客

开源 java android app 开发(八)通讯之Mqtt和Ble-优快云博客

开源 java android app 开发(九)后台之线程和服务-优快云博客

开源 java android app 开发(十)广播机制-优快云博客

开源 java android app 开发(十一)调试、发布-优快云博客

开源 java android app 开发(十二)封库.aar-优快云博客

推荐链接:

开源C# .net mvc 开发(一)WEB搭建_c#部署web程序-优快云博客

开源 C# .net mvc 开发(二)网站快速搭建_c#网站开发-优快云博客

开源 C# .net mvc 开发(三)WEB内外网访问(VS发布、IIS配置网站、花生壳外网穿刺访问)_c# mvc 域名下不可訪問內網,內網下可以訪問域名-优快云博客

开源 C# .net mvc 开发(四)工程结构、页面提交以及显示_c#工程结构-优快云博客

开源 C# .net mvc 开发(五)常用代码快速开发_c# mvc开发-优快云博客

本章内容主要是sqlite数据库,在鸿蒙系统上支持sqlite关系数据库,以及向量数据库。华为给的官方例子比较复杂,开发文档的代码没办法直接运行(可能版本太旧),这里做了一个简单的sqlite的CURD的例子,以便快速使用。

1.创建SqliteHelper数据库操作类。

2.修改主页面Index.etsd代码。

3.最终显示效果。

一、创建一个SqliteHelper数据库操作类

1.1基本操作

1.2  以下为SqliteHelper.ets代码

创建名为 myDatabase.db 的数据库

数据库初始化 (initDatabase())

addPerson(): 插入新记录

deletePerson(): 按ID删除记录

deleteWithCondition(): 按条件删除记录

queryAllPersons(): 查询所有记录

queryWithCondition(): 按条件查询记录

// SqliteHelper.ets
import relationalStore from '@ohos.data.relationalStore';
import common from '@ohos.app.ability.common';

interface Person {
  id: number;
  name: string;
  age: number;
  email: string;
}

export class SqliteHelper {
  private rdbStore: relationalStore.RdbStore | null = null;
  private readonly TABLE_NAME = 'PERSON';
  private readonly CREATE_TABLE_SQL = `CREATE TABLE IF NOT EXISTS ${this.TABLE_NAME} (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    name TEXT NOT NULL,
    age INTEGER,
    email TEXT
  )`;

  private context: common.UIAbilityContext;

  constructor(context: common.UIAbilityContext) {
    this.context = context;
  }

  async initDatabase(): Promise<boolean> {
    try {
      const config: relationalStore.StoreConfig = {
        name: 'myDatabase.db',
        securityLevel: relationalStore.SecurityLevel.S1
      };

      this.rdbStore = await relationalStore.getRdbStore(this.context, config);
      await this.rdbStore.executeSql(this.CREATE_TABLE_SQL);
      console.log('[sqlite] 数据库创建/初始化成功');
      return true;
    } catch (err) {
      console.error('[sqlite] 数据库初始化失败:', JSON.stringify(err));
      return false;
    }
  }

  async addPerson(name: string, age: number, email: string): Promise<boolean> {
    if (!this.rdbStore) {
      console.error('[sqlite] 数据库未初始化,无法添加数据');
      return false;
    }

    try {
      const valueBucket: relationalStore.ValuesBucket = {
        'name': name,
        'age': age,
        'email': email
      };
      await this.rdbStore.insert(this.TABLE_NAME, valueBucket);
      console.log('[sqlite] 添加数据成功');
      return true;
    } catch (err) {
      console.error('[sqlite] 添加数据失败:', JSON.stringify(err));
      return false;
    }
  }

  async deletePerson(id: number): Promise<boolean> {
    if (!this.rdbStore) {
      console.error('[sqlite] 数据库未初始化,无法删除数据');
      return false;
    }

    try {
      const predicates = new relationalStore.RdbPredicates(this.TABLE_NAME);
      predicates.equalTo('id', id);
      await this.rdbStore.delete(predicates);
      console.log('[sqlite] 删除数据成功');
      return true;
    } catch (err) {
      console.error('[sqlite] 删除数据失败:', JSON.stringify(err));
      return false;
    }
  }

  async queryAllPersons(): Promise<Person[]> {
    if (!this.rdbStore) {
      console.error('[sqlite] 数据库未初始化,无法查询数据');
      return [];
    }

    try {
      const predicates = new relationalStore.RdbPredicates(this.TABLE_NAME);
      const columns = ['id', 'name', 'age', 'email'];
      const resultSet = await this.rdbStore.query(predicates, columns);

      const persons: Person[] = [];
      while (resultSet.goToNextRow()) {
        persons.push({
          id: resultSet.getLong(resultSet.getColumnIndex('id')),
          name: resultSet.getString(resultSet.getColumnIndex('name')),
          age: resultSet.getLong(resultSet.getColumnIndex('age')),
          email: resultSet.getString(resultSet.getColumnIndex('email'))
        });
      }
      resultSet.close();

      console.log('[sqlite] 查询到数据:', JSON.stringify(persons));
      return persons;
    } catch (err) {
      console.error('[sqlite] 查询数据失败:', JSON.stringify(err));
      return [];
    }
  }




  // 条件删除
  async deleteWithCondition(whereClause: string): Promise<boolean> {
    if (!this.rdbStore) {
      console.error('[sqlite] 数据库未初始化,无法删除数据');
      return false;
    }

    try {
      const sql = `DELETE FROM ${this.TABLE_NAME} WHERE ${whereClause}`;
      await this.rdbStore.executeSql(sql);
      console.log('[sqlite] 条件删除成功');
      return true;
    } catch (err) {
      console.error('[sqlite] 条件删除失败:', JSON.stringify(err));
      return false;
    }
  }

  // 条件查询
  async queryWithCondition(whereClause: string): Promise<Person[]> {
    if (!this.rdbStore) {
      console.error('[sqlite] 数据库未初始化,无法查询数据');
      return [];
    }

    try {
      const sql = `SELECT * FROM ${this.TABLE_NAME} WHERE ${whereClause}`;
      const resultSet = await this.rdbStore.querySql(sql);

      const persons: Person[] = [];
      while (resultSet.goToNextRow()) {
        persons.push({
          id: resultSet.getLong(resultSet.getColumnIndex('id')),
          name: resultSet.getString(resultSet.getColumnIndex('name')),
          age: resultSet.getLong(resultSet.getColumnIndex('age')),
          email: resultSet.getString(resultSet.getColumnIndex('email'))
        });
      }
      resultSet.close();

      console.log('[sqlite] 条件查询结果:', JSON.stringify(persons));
      return persons;
    } catch (err) {
      console.error('[sqlite] 条件查询失败:', JSON.stringify(err));
      return [];
    }
  }
}

二、Index.ets的代码


// Index.ets
import { SqliteHelper } from './SqliteHelper';
import promptAction from '@ohos.promptAction';
import { common } from '@kit.AbilityKit';

interface Person {
  id: number;
  name: string;
  age: number;
  email: string;
}
@Entry
@Component
struct Index {
  private sqliteHelper: SqliteHelper = new SqliteHelper(getContext(this) as  common.UIAbilityContext);
  @State personList: Array<Person> = [];

  // 添加三个状态变量存储输入框内容
  @State nameInput: string = '';
  @State ageInput: string = '';
  @State emailInput: string = '';
  build() {
    Column() {
      Button('创建数据库')
        .onClick(() => {
          this.sqliteHelper.initDatabase().then(success => {
            if (success) {
              promptAction.showToast({ message: '数据库创建成功' });
            } else {
              promptAction.showToast({ message: '数据库创建失败' });
            }
          });
        })
        .margin(10)

      // 输入姓名
      TextInput({ placeholder: '请输入姓名' })
        .width('90%')
        .height(40)
        .margin(10)
        .onChange((value: string) => {
          this.nameInput = value;
        })

      // 输入年龄
      TextInput({ placeholder: '请输入年龄' })
        .width('90%')
        .height(40)
        .margin(10)
        .type(InputType.Number) // 设置为数字输入
        .onChange((value: string) => {
          this.ageInput = value;
        })

      // 输入邮箱
      TextInput({ placeholder: '请输入邮箱' })
        .width('90%')
        .height(40)
        .margin(10)
        .onChange((value: string) => {
          this.emailInput = value;
        })

      Row(){
        Button('添加数据')
          .onClick(() => {

            if (!this.nameInput || !this.ageInput || !this.emailInput) {
              promptAction.showToast({ message: '请填写完整信息' });
              return;
            }

            const age = parseInt(this.ageInput);
            if (isNaN(age)) {
              promptAction.showToast({ message: '年龄必须是数字' });
              return;
            }


            this.sqliteHelper.addPerson(this.nameInput, age, this.emailInput)
              .then(success => {
                promptAction.showToast({
                  message: success ? '数据添加成功' : '数据添加失败'
                });
                if (success) {
                  //this.clearInputs();
                  this.queryData(); // 添加成功后刷新列表
                }
              });
          })
          .margin(10)

        /*
    Button('删除第一条数据')
      .onClick(() => {
        /*his.personList.length > 0) {
          this.sqliteHelper.deletePerson(this.personList[0].id)
            .then(success => {
              if (success) {
                promptAction.showToast({ message: '数据删除成功' });
                this.queryData();
              } else {
                promptAction.showToast({ message: '数据删除失败' });
              }
            });
        } else {
          promptAction.showToast({ message: '没有数据可删除' });
        }
      })
      .margin(10)
      */
        Button('条件删除')
          .onClick(() => {
            if (!this.nameInput && !this.ageInput && !this.emailInput) {
              promptAction.showToast({ message: '请至少输入一个条件' });
              return;
            }

            // 构造删除条件
            const conditions: string[] = [];
            if (this.nameInput) conditions.push(`name = '${this.nameInput}'`);
            if (this.ageInput) conditions.push(`age = ${parseInt(this.ageInput)}`);
            if (this.emailInput) conditions.push(`email = '${this.emailInput}'`);

            const whereClause = conditions.join(' OR ');
            this.sqliteHelper.deleteWithCondition(whereClause)
              .then(success => {
                promptAction.showToast({
                  message: success ? '数据删除成功' : '数据删除失败'
                });
                if (success) {
                  //this.clearInputs();
                  this.queryData(); // 添加成功后刷新列表
                }
              });
          })
          .margin(10)
      }

      Row() {

        Button('查询所有')
          .onClick(() => {
            this.queryData();
          })
          .margin(10)

        Button('条件查询')
          .onClick(() => {
            if (!this.nameInput && !this.ageInput && !this.emailInput) {
              promptAction.showToast({ message: '请至少输入一个条件' });
              return;
            }

            // 构造删除条件
            const conditions: string[] = [];
            if (this.nameInput) conditions.push(`name = '${this.nameInput}'`);
            if (this.ageInput) conditions.push(`age = ${parseInt(this.ageInput)}`);
            if (this.emailInput) conditions.push(`email = '${this.emailInput}'`);

            const whereClause = conditions.join(' OR ');
            /*
            this.sqliteHelper.queryWithCondition(whereClause)
              .then(success => {
                promptAction.showToast({
                  message: success ? '数据查询成功' : '数据查询失败'
                });
                if (success) {
                  //this.clearInputs();
                  this.queryData(); // 添加成功后刷新列表
                }
              });
            */
            this.sqliteHelper.queryWithCondition(whereClause).then(persons => {
              this.personList = persons;
              if (persons.length === 0) {
                promptAction.showToast({ message: '没有查询到数据' });
              } else {
                promptAction.showToast({ message: `查询到${persons.length}条数据` });
              }
            });
          })
          .margin(10)
      }


      List({ space: 10 }) {
        ForEach(this.personList, (person: Person) => {
          ListItem() {
            Text(`ID: ${person.id}, 姓名: ${person.name}, 年龄: ${person.age}, 邮箱: ${person.email}`)
              .fontSize(16)
              .margin(10)
          }
        }, (person: Person) => person.id.toString())
      }
      .layoutWeight(1)
      .width('100%')
    }
    .width('100%')
    .height('100%')
    .padding(20)
  }



  private queryData() {
    this.sqliteHelper.queryAllPersons().then(persons => {
      this.personList = persons;
      if (persons.length === 0) {
        promptAction.showToast({ message: '没有查询到数据' });
      } else {
        promptAction.showToast({ message: `查询到${persons.length}条数据` });
      }
    });
  }
  // 清空输入框
  private clearInputs() {
    this.nameInput = '';
    this.ageInput = '';
    this.emailInput = '';
  }


}

三、最终显示效果,将手机的截图组合到一起,效果如下

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值