新聞中心
??想了解更多內(nèi)容,請(qǐng)?jiān)L問:??

??和華為官方合作共建的鴻蒙技術(shù)社區(qū)??
??https://ost.??
前言
項(xiàng)目需要用到數(shù)據(jù)持久化存儲(chǔ),沒有使用過HarmonyOS數(shù)據(jù)庫(kù)時(shí),我們就需要去官方文檔或其他渠道去學(xué)習(xí)怎么使用,但是官方文檔等長(zhǎng)長(zhǎng)的文字教程通常需要自己花很長(zhǎng)時(shí)間去學(xué)習(xí)和理解才能掌握那本可以很容易就上手的知識(shí)。本篇速成教程直接使用最精準(zhǔn)和簡(jiǎn)短的文字,再配上講解代碼,讓我們能在10分鐘左右就能掌握最基本的數(shù)據(jù)庫(kù)使用方法。數(shù)據(jù)庫(kù)的三大要素:數(shù)據(jù)庫(kù)、表、字段,接下來為大家介紹關(guān)系型數(shù)據(jù)庫(kù)和對(duì)象關(guān)系數(shù)據(jù)庫(kù)的使用方法。
關(guān)系型數(shù)據(jù)庫(kù)
在關(guān)系型數(shù)據(jù)庫(kù)中,負(fù)責(zé)對(duì)應(yīng)的類或創(chuàng)建的方式分別為:
- 數(shù)據(jù)庫(kù):RdbStore
- 表:通過RdbStore的executeSql方法,傳入對(duì)應(yīng)的sql語(yǔ)句創(chuàng)建表
- 字段:通過RdbStore的executeSql方法,傳入對(duì)應(yīng)的sql語(yǔ)句添加字段
建表和字段
// 如果不存在表student,則創(chuàng)建student表,并創(chuàng)建“id”(自增主鍵)、“name”(不為空)、“age”(integer類型)、“salary”(real類型)這4個(gè)字段
rdbStore.executeSql("create table if not exists student(id integer primary key autoincrement,name text not null, age integer, salary real)");
使用RdbStore類創(chuàng)建數(shù)據(jù)庫(kù)
根據(jù)數(shù)據(jù)庫(kù)操作的輔助類DatabaseHelper創(chuàng)建,并傳入對(duì)應(yīng)的數(shù)據(jù)庫(kù)配置對(duì)象、數(shù)據(jù)庫(kù)版本號(hào)、數(shù)據(jù)庫(kù)創(chuàng)建或升降級(jí)等操作的回調(diào)對(duì)象,創(chuàng)建RdbStore數(shù)據(jù)庫(kù)對(duì)象,并在數(shù)據(jù)庫(kù)創(chuàng)建的回調(diào)里新增對(duì)應(yīng)的表和字段,如下:
// 表名稱
private static String StudentTable = "student";
// 數(shù)據(jù)庫(kù)操作類
private RdbStore rdbStore;
// 數(shù)據(jù)庫(kù)輔助類
private DatabaseHelper helper;
// 根據(jù)slice創(chuàng)建數(shù)據(jù)庫(kù)輔助類
helper = new DatabaseHelper(context);
// 初始化數(shù)據(jù)庫(kù),包括數(shù)據(jù)庫(kù)的創(chuàng)建。
private void initDB() {
// 創(chuàng)建數(shù)據(jù)庫(kù)配置對(duì)象
StoreConfig config = StoreConfig.newDefaultConfig(StudentTable + ".db");
RdbOpenCallback callback = new RdbOpenCallback() {
@Override
public void onCreate(RdbStore rdbStore) {
rdbStore.executeSql("create table if not exists student(id integer primary key autoincrement,name text not null, age integer, salary real)");
}
@Override
public void onUpgrade(RdbStore rdbStore, int i, int i1) {
}
};
// 1為數(shù)據(jù)庫(kù)的版本號(hào)
rdbStore = helper.getRdbStore(config,1,callback);
}
既然拿到了數(shù)據(jù)庫(kù)操作類RdbStore,我們就可以對(duì)數(shù)據(jù)庫(kù)進(jìn)行增刪改查的操作了:
新增數(shù)據(jù)操作:
// 添加數(shù)據(jù)
public boolean insertStudent(Student student){
ValuesBucket bucket = new ValuesBucket();
bucket.putInteger("age",student.getAge());
bucket.putString("name", student.getName());
bucket.putDouble("salary", student.getSalary());
long id = rdbStore.insert(StudentTable, bucket);
return id > 0 ? true : false;
}
刪除、修改、查詢等操作,都需要配合謂詞AbsRdbPredicates的子類RdbPredicates進(jìn)行:
刪除數(shù)據(jù)操作:
// 刪除數(shù)據(jù):刪除StudentTable表中對(duì)應(yīng)的id那一條數(shù)據(jù)
public boolean deleteStudent(Integer id){
RdbPredicates predicates = new RdbPredicates(StudentTable);
predicates.equalTo("id", id);
int res = rdbStore.delete(predicates);
return res > 0 ? true : false;
}
修改數(shù)據(jù)操作:
/*
* 修改數(shù)據(jù):修改StudentTable表中對(duì)應(yīng)id的那一條數(shù)據(jù)
* 以下更新語(yǔ)句相當(dāng)于執(zhí)行了:
* update student set name=?, age=?, salary=? where id = ?
*/
public boolean updateStudent(Student student){
RdbPredicates predicates = new RdbPredicates(StudentTable);
// 以下代碼相當(dāng)于執(zhí)行了 where id = ?
predicates.equalTo("id", student.getId());
ValuesBucket bucket = new ValuesBucket();
bucket.putInteger("age",student.getAge());
bucket.putString("name", student.getName());
bucket.putDouble("salary", student.getSalary());
int id = rdbStore.update(bucket, predicates);
return id > 0 ? true : false;
}
查詢數(shù)據(jù)操作:
// 查詢數(shù)據(jù):查詢StudentTable表中所有包含指定name的數(shù)據(jù)
public ListqueryStudents(String name){
// String[]為想要查詢的字段
String[] strings = new String[]{
"id", "age", "name", "salary"
};
RdbPredicates predicates = new RdbPredicates(StudentTable);
predicates.like("name", name);
// ResultSet:查詢的結(jié)果都包含在這個(gè)對(duì)象里邊
ResultSet resultSet = rdbStore.query(predicates, strings);
Liststudents = new ArrayList<>();
// resultSet.goToNextRow()為true時(shí),表示還有下一條數(shù)據(jù),并指定到下一條數(shù)據(jù)
while (resultSet.goToNextRow()){
Student student = new Student();
student.setId(resultSet.getInt(resultSet.getColumnIndexForName("id")));
student.setAge(resultSet.getInt(resultSet.getColumnIndexForName("age")));
student.setName(resultSet.getString(resultSet.getColumnIndexForName("name")));
student.setSalary(resultSet.getDouble(resultSet.getColumnIndexForName("salary")));
students.add(student);
}
return students;
}
對(duì)象型數(shù)據(jù)庫(kù)
配置“build.gradle”文件:
1、如果使用注解處理器的模塊為“com.huawei.ohos.hap”模塊,則需要在模塊的“build.gradle”文件的ohos節(jié)點(diǎn)中添加以下配置:
compileOptions{
annotationEnabled true
} 2、如果使用注解處理器的模塊為“com.huawei.ohos.library”模塊,則需要在模塊的“build.gradle”文件的“dependencies”節(jié)點(diǎn)中配置注解處理器。
查看“orm_annotations_java.jar”、“orm_annotations_processor_java.jar” 、“javapoet_java.jar”這3個(gè)jar包在HUAWEI SDK中的Sdk/java/x.x.x.xx/build-tools/lib/目錄,并將目錄的這三個(gè)jar包導(dǎo)進(jìn)來。
dependencies {
compile files("orm_annotations_java.jar的路徑", "orm_annotations_processor_java.jar的路徑", "javapoet_java.jar的路徑")
annotationProcessor files("orm_annotations_java.jar的路徑", "orm_annotations_processor_java.jar的路徑", "javapoet_java.jar的路徑")
}如下圖所示配置:
在對(duì)象型數(shù)據(jù)庫(kù)中,負(fù)責(zé)操作對(duì)應(yīng)三大要素的類分別為:
數(shù)據(jù)庫(kù):被開發(fā)者用@Database注解,且繼承了OrmDatabase的類,對(duì)應(yīng)關(guān)系型數(shù)據(jù)庫(kù)。
// 定義了一個(gè)數(shù)據(jù)庫(kù)類UserStore.java,數(shù)據(jù)庫(kù)包含了“User”,"Book","AllDataType"三個(gè)表,版本號(hào)為“1”。數(shù)據(jù)庫(kù)類的getVersion方法和getHelper方法不需要實(shí)現(xiàn),直接將數(shù)據(jù)庫(kù)類設(shè)為虛類即可。
@Database(entities = {User.class, Book.class, AllDataType.class}, version = 1)
public abstract class UserStore extends OrmDatabase {
}
表:被開發(fā)者用@Entity注解的實(shí)體類,且繼承了OrmObject的類,對(duì)應(yīng)關(guān)系型數(shù)據(jù)庫(kù)中的表。
// 定義了一個(gè)實(shí)體類User.java,對(duì)應(yīng)數(shù)據(jù)庫(kù)內(nèi)的表名為“user”;indices 為“firstName”和“l(fā)astName”兩個(gè)字段建立了復(fù)合索引“name_index”,并且索引值是唯一的;“ignoredColumns”表示該字段不需要添加到“user”表的屬性中。
@Entity(tableName = "user", ignoredColumns = {"ignoredColumn1", "ignoredColumn2"},
indices = {@Index(value = {"firstName", "lastName"}, name = "name_index", unique = true)})
public class User extends OrmObject {
// 此處將userId設(shè)為了自增的主鍵。注意只有在數(shù)據(jù)類型為包裝類型時(shí),自增主鍵才能生效。
// 注意:實(shí)體類至少要聲明一個(gè)主鍵并實(shí)現(xiàn)對(duì)應(yīng)的getter和setter方法,不然會(huì)編譯報(bào)錯(cuò)!
@PrimaryKey(autoGenerate = true)
private Integer userId;
private String firstName;
private String lastName;
private int age;
private double balance;
private int ignoredColumn1;
private int ignoredColumn2;
// 需添加各字段的getter和setter方法。
public Integer getUserId() {
return userId;
}
public void setUserId(Integer userId) {
this.userId = userId;
}
...
}
字段:對(duì)應(yīng)實(shí)體類的屬性
在HarmonyOS的對(duì)象型數(shù)據(jù)庫(kù)中,有一個(gè)最重要的負(fù)責(zé)對(duì)象數(shù)據(jù)操作接口的類:OrmContext。
對(duì)象數(shù)據(jù)操作接口類OrmContext配合謂詞接口OrmPredicate等,就可以實(shí)現(xiàn)對(duì)數(shù)據(jù)庫(kù)的增刪改查功能!如下為數(shù)據(jù)庫(kù)的增刪改查操作:
// 插入數(shù)據(jù)
public boolean insertUser(User user){
boolean flag = ormContext.insert(user);
return ormContext.flush();
}
// 刪除數(shù)據(jù):刪除User表中,對(duì)應(yīng)userId的那一條數(shù)據(jù)。
public boolean deleteUser(Integer userId){
OrmPredicates predicates = ormContext.where(User.class).equalTo("userId", userId);
int flag = ormContext.delete(predicates);
return flag > 0 ? true : false;
}
// 修改數(shù)據(jù):修改User表中對(duì)應(yīng)userId的那一條數(shù)據(jù)。
public boolean updateUser(Integer userId, User user){
ValuesBucket bucket = new ValuesBucket();
bucket.putInteger("age",user.getAge());
bucket.putString("firstName", user.getFirstName());
bucket.putString("lastName",user.getLastName());
bucket.putDouble("balance",user.getBalance());
OrmPredicates predicates = ormContext.where(user.getClass()).equalTo("userId", userId);
int row_id = ormContext.update(predicates, bucket);
return row_id > 0 ? true : false;
}
// 查詢數(shù)據(jù):查詢User表中包含對(duì)應(yīng)firstName的所有數(shù)據(jù)。
public ListqueryUsersWithFirstName(String firstName){
OrmPredicates predicates = ormContext.where(User.class).like("firstName", firstName);
Listusers = ormContext.query(predicates);
return users;
}
那ormContext是怎么創(chuàng)建出來的呢?
// 數(shù)據(jù)庫(kù)名稱
private String database_name = "mydb.db";
// 數(shù)據(jù)庫(kù)別名
private String database_name_alias = "mydb";
DatabaseHelper helper = new DatabaseHelper(context);
// UserStore.class:數(shù)據(jù)庫(kù)類
ormContext = helper.getOrmContext(database_name_alias, database_name, UserStore.class);
DatabaseHelper是數(shù)據(jù)庫(kù)操作的輔助類,當(dāng)數(shù)據(jù)庫(kù)創(chuàng)建成功后,數(shù)據(jù)庫(kù)文件將存儲(chǔ)在由上下文指定的目錄里。注意:context入?yún)㈩愋蜑閛hos.app.Context,注意不要使用slice.getContext()來獲取context,請(qǐng)直接傳入slice,否則會(huì)出現(xiàn)找不到類的報(bào)錯(cuò)。
總結(jié)
此文章用較小的篇幅講解了最基本的HarmonyOS中關(guān)系型數(shù)據(jù)庫(kù)和對(duì)象型數(shù)據(jù)庫(kù)的使用,使讀者能夠快速理解和上手相關(guān)的知識(shí)和操作,當(dāng)讀者上手了這篇文章時(shí),再去看其他更全更深層次的知識(shí),相信會(huì)更加容易讀懂和上手。
??想了解更多內(nèi)容,請(qǐng)?jiān)L問:??
??和華為官方合作共建的鴻蒙技術(shù)社區(qū)??
??https://ost.??
網(wǎng)站欄目:HarmonyOS—十分鐘教會(huì)數(shù)據(jù)庫(kù)快速上手
網(wǎng)站URL:http://m.fisionsoft.com.cn/article/cojphgi.html


咨詢
建站咨詢
