美文网首页
零基础学鸿蒙编程-轻量级数据库

零基础学鸿蒙编程-轻量级数据库

作者: 蓝不蓝编程 | 来源:发表于2021-11-02 09:06 被阅读0次

什么是轻量级数据库

轻量级数据库是一种以键值对形式保存数据的存储方式.每条数据都需要指定一个唯一键名来进行区分.可以存储布尔型、整型、字符串等基础数据类型.其特点为简单、轻量,适合保存少量简单类型的数据,不适合保存大批量或复杂类型的数据.

基础样例

1. 写入和读取数据

  1. java代码
public class MainAbilitySlice extends AbilitySlice {
    private Preferences preferences;

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_main);

        DatabaseHelper databaseHelper = new DatabaseHelper(getContext());
        String filename = "pdb";
        preferences = databaseHelper.getPreferences(filename);

        findComponentById(ResourceTable.Id_writeText).setClickedListener(component -> write());
        findComponentById(ResourceTable.Id_readText).setClickedListener(component -> read());
        findComponentById(ResourceTable.Id_modifyText).setClickedListener(component -> modify());
        findComponentById(ResourceTable.Id_delText).setClickedListener(component -> del());
    }

    private void write() {
        preferences.putString("name", "花生皮编程");
        preferences.flush();
    }

    private void read() {
        String name = preferences.getString("name", "数据不存在");
        new ToastDialog(getContext()).setText(name).show();
    }

    private void modify() {
        preferences.putString("name", "花生皮编程2");
        preferences.flush();
    }

    private void del() {
        preferences.delete("name");
    }
}
  1. 对应页面布局文件:
<?xml version="1.0" encoding="utf-8"?>
<DirectionalLayout
    xmlns:ohos="http://schemas.huawei.com/res/ohos"
    ohos:height="match_parent"
    ohos:width="match_parent"
    ohos:alignment="center"
    ohos:orientation="vertical">

    <Text
        ohos:id="$+id:writeText"
        ohos:height="match_content"
        ohos:width="match_content"
        ohos:text="写数据"
        ohos:text_size="20fp"/>

    <Text
        ohos:id="$+id:readText"
        ohos:height="match_content"
        ohos:width="match_content"
        ohos:text="读数据"
        ohos:text_size="20fp"/>

    <Text
        ohos:id="$+id:modifyText"
        ohos:height="match_content"
        ohos:width="match_content"
        ohos:text="修改数据"
        ohos:text_size="20fp"/>

    <Text
        ohos:id="$+id:delText"
        ohos:height="match_content"
        ohos:width="match_content"
        ohos:text="删除数据"
        ohos:text_size="20fp"/>
</DirectionalLayout>

常用函数说明

函数名 用途
putString 存储字符串类型数据
putInt 存储整型数据
putLong 存储长整型数据
putFloat 存储浮点型数据
putBoolean 存储布尔值,true或false
putStringSet 存储字符串集合
delete 删除指定键名对应的数据记录
clear 清空所有存储的数据
apply 修改数据后,提交保存到文件中
getString 以字符串类型读取出数据
getInt 以整型读取出数据
getLong 以长整型读取出数据
getFloat 以浮点型读取出数据
getBoolean 以布尔值读取出数据

完整源代码

https://gitee.com/hspbc/harmonyos_demos/tree/master/preferenceDemo

关于我

厦门大学计算机专业 | 前华为工程师
分享编程技术,没啥深度,但看得懂,适合初学者。
Java | 安卓 | 前端 | 小程序 | 鸿蒙

相关文章

网友评论

      本文标题:零基础学鸿蒙编程-轻量级数据库

      本文链接:https://www.haomeiwen.com/subject/zkmzaltx.html