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

鸿蒙时代
发布于 2021-9-13 14:53
浏览
1收藏

1.创建一个空的java项目
HarmonyOS应用开发数据交互--关系型数据库完整流程练习-鸿蒙开发者社区

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

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

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

配置文件(这部分自动生成,与你的目录结果、建议不要修改):

{

“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”

}

3.编写创建数据库代码
编写的fristRDB.java文件:

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) 的方法。

//   RdbOpenCallback 管理数据库创建、升级和降级。

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);

}

}

4.编写数据操作代码
为了方便在在MainAbility上编写数据库操作代码。

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");

    }

}

}

5.查看结果
在虚拟机上运行后,打开Hilog,搜索查看输出的内容。
HarmonyOS应用开发数据交互--关系型数据库完整流程练习-鸿蒙开发者社区
HarmonyOS应用开发数据交互--关系型数据库完整流程练习-鸿蒙开发者社区

完整代码地址:

https://gitee.com/jltfcloudcn/jump_to/tree/master/HarmonyOS关系型数据库练习/HarmonyOS关系型数据库练习

分类
标签
HarmonyOS应用开发--关系型数据库案例练习.docx 260.51K 79次下载
2
收藏 1
回复
举报
回复
    相关推荐