HarmonyOS鸿蒙Next应用开发数据交互--关系型数据库完整流程练习

HarmonyOS鸿蒙Next应用开发数据交互–关系型数据库完整流程练习

  • 创建一个空的java项目

  • 创建data Ability

  • 如下步骤所示,创建完成后会生成相应的文件,同时会帮您修改好配置文件。

{
  "permissions": [
    "com.example.rdb.DataAbilityShellProvider.PROVIDER"
  ],
  "name": "com.example.rdb.Database.fristRDB",
  "icon": "$media:icon",
  "description": "$string:fristrdb_description",
  "type": "data",
  "visible": false,
  "uri": "dataability://com.example.rdb.Database.fristRDB"
}
  • 编写创建数据库代码
package com.example.rdb.Database;

import ohos.aafwk.ability.Ability;
import ohos.aafwk.ability.DataAbilityHelper;
import ohos.aafwk.content.Intent;
import ohos.data.DatabaseHelper;
import ohos.data.dataability.DataAbilityUtils;
import ohos.data.rdb.*;
import ohos.data.resultset.ResultSet;
import ohos.data.dataability.DataAbilityPredicates;
import ohos.hiviewdfx.HiLog;
import ohos.hiviewdfx.HiLogLabel;
import ohos.utils.net.Uri;
import ohos.utils.PacMap;
import java.io.FileDescriptor;

public class fristRDB extends Ability {
    private static final String DB_NAME = "persondataability.db"; //数据库名称
    private static final String DB_TAB_NAME = "person"; //表名称
    private static final String DB_COLUMN_PERSON_ID = "id"; //列 id
    private static final String DB_COLUMN_NAME = "name"; //列 name
    private static final String DB_COLUMN_GENDER = "gender"; //列 gender
    private static final String DB_COLUMN_AGE = "age"; //列 age
    private static final int DB_VERSION = 1; //版本
    private static final HiLogLabel LABEL_LOG = new HiLogLabel(3, 0xD001100, "Demo");

    private StoreConfig config = StoreConfig.newDefaultConfig(DB_NAME); //通过指定数据库名称使用默认配置创建数据库配置。
    private RdbStore rdbStore; //提供管理关系数据库 (RDB) 的方法。

    private RdbOpenCallback rdbOpenCallback = new RdbOpenCallback() {
        @Override
        public void onCreate(RdbStore store) { // 数据库创建时被回调,开发者可以在该方法中初始化表结构,并添加一些应用使用到的初始化数据。
            store.executeSql("create table if not exists "
                    + DB_TAB_NAME + " ("
                    + DB_COLUMN_PERSON_ID + " integer primary key, "
                    + DB_COLUMN_NAME + " text not null, "
                    + DB_COLUMN_GENDER + " text not null, "
                    + DB_COLUMN_AGE + " integer)");
        }

        @Override
        public void onUpgrade(RdbStore store, int oldVersion, int newVersion) {
        }
    };

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        HiLog.info(LABEL_LOG, "fristRDB onStart");
        DatabaseHelper databaseHelper = new DatabaseHelper(this);
        // 根据配置创建或打开数据库。
        rdbStore = databaseHelper.getRdbStore(config, DB_VERSION, rdbOpenCallback, null);
    }

    /**
     * 数据查询
     * @param uri
     * @param columns
     * @param predicates
     * @return
     */
    @Override
    public ResultSet query(Uri uri, String[] columns, DataAbilityPredicates predicates) {
        // 拼装查询语句
        RdbPredicates rdbPredicates = DataAbilityUtils.createRdbPredicates(predicates, DB_TAB_NAME);
        // 查询表中数据 根据 查询语句 + 查找的列
        ResultSet resultSet = rdbStore.query(rdbPredicates, columns);
        if (resultSet == null) {
            HiLog.info(LABEL_LOG, "resultSet is null");
        }
        return resultSet;
    }

    /**
     * 数据添加
     * @param uri 插入的目标路径
     * @param value 插入的数据值
     * @return
     */
    @Override
    public int insert(Uri uri, ValuesBucket value) {
        HiLog.info(LABEL_LOG, "fristRDB insert");
        String path = uri.getLastPath();
        // 判断数据添加的表名称
        if (!"person".equals(path)) {
            HiLog.info(LABEL_LOG, "DataAbility insert path is not matched");
            return -1;
        }
        // 用于整理存储添加的数据
        ValuesBucket values = new ValuesBucket();
        values.putInteger(DB_COLUMN_PERSON_ID, value.getInteger(DB_COLUMN_PERSON_ID));
        values.putString(DB_COLUMN_NAME, value.getString(DB_COLUMN_NAME));
        values.putString(DB_COLUMN_GENDER, value.getString(DB_COLUMN_GENDER));
        values.putInteger(DB_COLUMN_AGE, value.getInteger(DB_COLUMN_AGE));
        int index = (int) rdbStore.insert(DB_TAB_NAME, values);
        // 当表格数据插入成功时,可执行DataAbilityHelper.creator(this, uri).notifyChange(uri),通知该表格数据的订阅者
        DataAbilityHelper.creator(this, uri).notifyChange(uri);
        return index;
    }

    /**
     * 数据删除
     * @param uri 删除的目标路径
     * @param predicates 删除条件
     * @return
     */
    @Override
    public int delete(Uri uri, DataAbilityPredicates predicates) {
        // 解析出要删除的数据
        RdbPredicates rdbPredicates = DataAbilityUtils.createRdbPredicates(predicates, DB_TAB_NAME);
        int index = rdbStore.delete(rdbPredicates);
        HiLog.info(LABEL_LOG, "delete: " + index);
        // 通知观察者数据已经修改
        DataAbilityHelper.creator(this, uri).notifyChange(uri);
        return index;
    }

    /**
     * 数据修改
     * @param uri
     * @param value
     * @param predicates
     * @return
     */
    @Override
    public int update(Uri uri, ValuesBucket value, DataAbilityPredicates predicates) {
        // 解析出要修改的数据
        RdbPredicates rdbPredicates = DataAbilityUtils.createRdbPredicates(predicates, DB_TAB_NAME);
        int index = rdbStore.update(value, rdbPredicates);
        HiLog.info(LABEL_LOG, "update: " + index);
        // 通知观察者数据已经修改
        DataAbilityHelper.creator(this, uri).notifyChange(uri);
        return index;
    }

    @Override
    public FileDescriptor openFile(Uri uri, String mode) {
        return null;
    }

    @Override
    public String[] getFileTypes(Uri uri, String mimeTypeFilter) {
        return new String[0];
    }

    @Override
    public PacMap call(String method, String arg, PacMap extras) {
        return null;
    }

    @Override
    public String getType(Uri uri) {
        return null;
    }

    public void myInsert(){
        ValuesBucket values = new ValuesBucket();
        values.putInteger("id", 1);
        values.putString("name", "zhangsan");
        values.putInteger("age", 18);
        long id = rdbStore.insert("person", values);
    }
}
  • 编写数据操作代码
package com.example.rdb.slice;

import com.example.rdb.Database.MyDataAbilityHelper;
import com.example.rdb.ResourceTable;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.ability.DataAbilityHelper;
import ohos.aafwk.ability.DataAbilityRemoteException;
import ohos.aafwk.content.Intent;
import ohos.app.Context;
import ohos.data.dataability.DataAbilityPredicates;
import ohos.data.rdb.RdbStore;
import ohos.data.rdb.ValuesBucket;
import ohos.data.resultset.ResultSet;
import ohos.hiviewdfx.HiLog;
import ohos.hiviewdfx.HiLogLabel;
import ohos.utils.net.Uri;

public class MainAbilitySlice extends AbilitySlice {
    private static final HiLogLabel LABEL_LOG = new HiLogLabel(3, 0xD001100, "Demo");
    private static final String BASE_URI = "dataability:///com.example.rdb.Database.fristRDB";
    private static final String DATA_PATH = "/person";
    private static final String DB_COLUMN_PERSON_ID = "id";
    private static final String DB_COLUMN_NAME = "name";
    private static final String DB_COLUMN_GENDER = "gender";
    private static final String DB_COLUMN_AGE = "age";
    private DataAbilityHelper databaseHelper = DataAbilityHelper.creator((Context) this);

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_main);
        databaseHelper = DataAbilityHelper.creator(this);
        insert(33, "Tom", "man", 20);
        query();
        delete(33);
    }

    @Override
    public void onActive() {
        super.onActive();
    }

    @Override
    public void onForeground(Intent intent) {
        super.onForeground(intent);
    }

    public void query() {
        String[] columns = new String[] {DB_COLUMN_PERSON_ID, DB_COLUMN_NAME, DB_COLUMN_GENDER, DB_COLUMN_AGE};
        // 构造查询条件
        DataAbilityPredicates predicates = new DataAbilityPredicates();
        predicates.between(DB_COLUMN_AGE, 15, 40);
        try {
            ResultSet resultSet = databaseHelper.query(Uri.parse(BASE_URI + DATA_PATH),
                    columns, predicates);
            if (resultSet == null || resultSet.getRowCount() == 0) {
                HiLog.info(LABEL_LOG, "query: resultSet is null or no result found");
                return;
            }
            // 移动到第一行
            resultSet.goToFirstRow();
            do {
                int id = resultSet.getInt(resultSet.getColumnIndexForName(DB_COLUMN_PERSON_ID));
                String name = resultSet.getString(resultSet.getColumnIndexForName(DB_COLUMN_NAME));
                String gender = resultSet.getString(resultSet.getColumnIndexForName(DB_COLUMN_GENDER));
                int age = resultSet.getInt(resultSet.getColumnIndexForName(DB_COLUMN_AGE));
                HiLog.info(LABEL_LOG, "query: Id :" + id + " Name :" + name + " Gender :" + gender + " Age :" + age);
            } while (resultSet.goToNextRow()); //移动到下一行一行
        } catch (DataAbilityRemoteException | IllegalStateException exception) {
            HiLog.error(LABEL_LOG, "query: dataRemote exception | illegalStateException");
        }
    }

    public void insert(int id, String name, String gender, int age) {
        ValuesBucket valuesBucket = new ValuesBucket();
        valuesBucket.putInteger(DB_COLUMN_PERSON_ID, id);
        valuesBucket.putString(DB_COLUMN_NAME, name);
        valuesBucket.putString(DB_COLUMN_GENDER, gender);
        valuesBucket.putInteger(DB_COLUMN_AGE, age);
        HiLog.info(LABEL_LOG, "valuesBucket:" + valuesBucket);
        try {
            if (databaseHelper.insert(Uri.parse(BASE_URI + DATA_PATH), valuesBucket) != -1) {
                HiLog.info(LABEL_LOG, "insert successful");
            }
        } catch (DataAbilityRemoteException | IllegalStateException exception) {
            HiLog.error(LABEL_LOG, "insert: dataRemote exception|illegalStateException");
        }
    }

    public void update() {
        DataAbilityPredicates predicates = new DataAbilityPredicates();
        predicates.equalTo(DB_COLUMN_PERSON_ID, 102);
        ValuesBucket valuesBucket = new ValuesBucket();
        valuesBucket.putString(DB_COLUMN_NAME, "ZhangSanPlus");
        valuesBucket.putInteger(DB_COLUMN_AGE, 28);
        try {
            if (databaseHelper.update(Uri.parse(BASE_URI + DATA_PATH), valuesBucket, predicates) != -1) {
                HiLog.info(LABEL_LOG, "update successful");
            }
        } catch (DataAbilityRemoteException | IllegalStateException exception) {
            HiLog.error(LABEL_LOG, "update: dataRemote exception | illegalStateException");
        }
    }

    public void delete(int id) {
        DataAbilityPredicates predicates = new DataAbilityPredicates()
                .equalTo(DB_COLUMN_PERSON_ID, id);
        try {
            if (databaseHelper.delete(Uri.parse(BASE_URI + DATA_PATH), predicates) != -1) {
                HiLog.info(LABEL_LOG, "delete successful");
            }
        } catch (DataAbilityRemoteException | IllegalStateException exception) {
            HiLog.error(LABEL_LOG, "delete: dataRemote exception | illegalStateException");
        }
    }
}
  • 查看结果

在虚拟机上运行后,打开Hilog,搜索查看输出的内容。

完整代码地址: https://gitee.com/jltfcloudcn/jump_to/tree/master/HarmonyOS%E5%85%B3%E7%B3%BB%E5%9E%8B%E6%95%B0%E6%8D%AE%E5%BA%93%E7%BB%83%E4%B9%A0/HarmonyOS%E5%85%B3%E7%B3%BB%E5%9E%8B%E6%95%B0%E6%8D%AE%E5%BA%93%E7%BB%83%E4%B9%A0

5 回复

请问有没有数据变化订阅的完整例子啊?卡在这里了。

更多关于HarmonyOS鸿蒙Next应用开发数据交互--关系型数据库完整流程练习的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html


看到了自己和大佬的差距…

讲的很详细,很完整,谢谢分享

干货满满,看完文章,我觉得自己又行了……

在HarmonyOS鸿蒙Next中进行关系型数据库开发,完整流程如下:

  1. 创建数据库:使用RdbStore接口创建数据库,定义表结构。
  2. 插入数据:通过insert方法将数据插入到表中。
  3. 查询数据:使用query方法执行SQL查询,获取数据。
  4. 更新数据:通过update方法修改已有数据。
  5. 删除数据:使用delete方法删除表中的记录。
  6. 事务处理:通过beginTransactioncommitrollback确保数据一致性。

示例代码:

RdbStore store = helper.getRdbStore();
store.executeSql("CREATE TABLE IF NOT EXISTS user (id INTEGER PRIMARY KEY, name TEXT)");
store.insert("user", new ValuesBucket().putString("name", "Alice"));
Cursor cursor = store.query("user", new String[]{"name"}, null);
回到顶部
AI 助手
你好,我是IT营的 AI 助手
您可以尝试点击下方的快捷入口开启体验!