zl程序教程

您现在的位置是:首页 >  数据库

当前栏目

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

2023-09-27 14:27:30 时间

什么是轻量级数据库

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

基础样例

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编程》
《零基础学鸿蒙编程》

关于我

厦门大学计算机专业 | 前华为工程师
专注《零基础学编程系列》,包含:Java | 安卓 | 前端 | Flutter | iOS | 小程序 | 鸿蒙
全网可关注:花生皮编程