新聞中心
??想了解更多內容,請訪問:??

??和華為官方合作共建的鴻蒙技術社區(qū)??
??https://ost.??
前言
項目需要用到數(shù)據(jù)持久化存儲,沒有使用過HarmonyOS數(shù)據(jù)庫時,我們就需要去官方文檔或其他渠道去學習怎么使用,但是官方文檔等長長的文字教程通常需要自己花很長時間去學習和理解才能掌握那本可以很容易就上手的知識。本篇速成教程直接使用最精準和簡短的文字,再配上講解代碼,讓我們能在10分鐘左右就能掌握最基本的數(shù)據(jù)庫使用方法。數(shù)據(jù)庫的三大要素:數(shù)據(jù)庫、表、字段,接下來為大家介紹關系型數(shù)據(jù)庫和對象關系數(shù)據(jù)庫的使用方法。
關系型數(shù)據(jù)庫
在關系型數(shù)據(jù)庫中,負責對應的類或創(chuàng)建的方式分別為:
- 數(shù)據(jù)庫:RdbStore
- 表:通過RdbStore的executeSql方法,傳入對應的sql語句創(chuàng)建表
- 字段:通過RdbStore的executeSql方法,傳入對應的sql語句添加字段
建表和字段
// 如果不存在表student,則創(chuàng)建student表,并創(chuàng)建“id”(自增主鍵)、“name”(不為空)、“age”(integer類型)、“salary”(real類型)這4個字段
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ù)庫
根據(jù)數(shù)據(jù)庫操作的輔助類DatabaseHelper創(chuàng)建,并傳入對應的數(shù)據(jù)庫配置對象、數(shù)據(jù)庫版本號、數(shù)據(jù)庫創(chuàng)建或升降級等操作的回調對象,創(chuàng)建RdbStore數(shù)據(jù)庫對象,并在數(shù)據(jù)庫創(chuàng)建的回調里新增對應的表和字段,如下:
// 表名稱
private static String StudentTable = "student";
// 數(shù)據(jù)庫操作類
private RdbStore rdbStore;
// 數(shù)據(jù)庫輔助類
private DatabaseHelper helper;
// 根據(jù)slice創(chuàng)建數(shù)據(jù)庫輔助類
helper = new DatabaseHelper(context);
// 初始化數(shù)據(jù)庫,包括數(shù)據(jù)庫的創(chuàng)建。
private void initDB() {
// 創(chuàng)建數(shù)據(jù)庫配置對象
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ù)庫的版本號
rdbStore = helper.getRdbStore(config,1,callback);
}
既然拿到了數(shù)據(jù)庫操作類RdbStore,我們就可以對數(shù)據(jù)庫進行增刪改查的操作了:
新增數(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進行:
刪除數(shù)據(jù)操作:
// 刪除數(shù)據(jù):刪除StudentTable表中對應的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表中對應id的那一條數(shù)據(jù)
* 以下更新語句相當于執(zhí)行了:
* update student set name=?, age=?, salary=? where id = ?
*/
public boolean updateStudent(Student student){
RdbPredicates predicates = new RdbPredicates(StudentTable);
// 以下代碼相當于執(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:查詢的結果都包含在這個對象里邊
ResultSet resultSet = rdbStore.query(predicates, strings);
Liststudents = new ArrayList<>();
// resultSet.goToNextRow()為true時,表示還有下一條數(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;
}
對象型數(shù)據(jù)庫
配置“build.gradle”文件:
1、如果使用注解處理器的模塊為“com.huawei.ohos.hap”模塊,則需要在模塊的“build.gradle”文件的ohos節(jié)點中添加以下配置:
compileOptions{
annotationEnabled true
} 2、如果使用注解處理器的模塊為“com.huawei.ohos.library”模塊,則需要在模塊的“build.gradle”文件的“dependencies”節(jié)點中配置注解處理器。
查看“orm_annotations_java.jar”、“orm_annotations_processor_java.jar” 、“javapoet_java.jar”這3個jar包在HUAWEI SDK中的Sdk/java/x.x.x.xx/build-tools/lib/目錄,并將目錄的這三個jar包導進來。
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的路徑")
}如下圖所示配置:
在對象型數(shù)據(jù)庫中,負責操作對應三大要素的類分別為:
數(shù)據(jù)庫:被開發(fā)者用@Database注解,且繼承了OrmDatabase的類,對應關系型數(shù)據(jù)庫。
// 定義了一個數(shù)據(jù)庫類UserStore.java,數(shù)據(jù)庫包含了“User”,"Book","AllDataType"三個表,版本號為“1”。數(shù)據(jù)庫類的getVersion方法和getHelper方法不需要實現(xiàn),直接將數(shù)據(jù)庫類設為虛類即可。
@Database(entities = {User.class, Book.class, AllDataType.class}, version = 1)
public abstract class UserStore extends OrmDatabase {
}
表:被開發(fā)者用@Entity注解的實體類,且繼承了OrmObject的類,對應關系型數(shù)據(jù)庫中的表。
// 定義了一個實體類User.java,對應數(shù)據(jù)庫內的表名為“user”;indices 為“firstName”和“l(fā)astName”兩個字段建立了復合索引“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ù)據(jù)類型為包裝類型時,自增主鍵才能生效。
// 注意:實體類至少要聲明一個主鍵并實現(xiàn)對應的getter和setter方法,不然會編譯報錯!
@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;
}
...
}
字段:對應實體類的屬性
在HarmonyOS的對象型數(shù)據(jù)庫中,有一個最重要的負責對象數(shù)據(jù)操作接口的類:OrmContext。
對象數(shù)據(jù)操作接口類OrmContext配合謂詞接口OrmPredicate等,就可以實現(xiàn)對數(shù)據(jù)庫的增刪改查功能!如下為數(shù)據(jù)庫的增刪改查操作:
// 插入數(shù)據(jù)
public boolean insertUser(User user){
boolean flag = ormContext.insert(user);
return ormContext.flush();
}
// 刪除數(shù)據(jù):刪除User表中,對應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表中對應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表中包含對應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ù)庫名稱
private String database_name = "mydb.db";
// 數(shù)據(jù)庫別名
private String database_name_alias = "mydb";
DatabaseHelper helper = new DatabaseHelper(context);
// UserStore.class:數(shù)據(jù)庫類
ormContext = helper.getOrmContext(database_name_alias, database_name, UserStore.class);
DatabaseHelper是數(shù)據(jù)庫操作的輔助類,當數(shù)據(jù)庫創(chuàng)建成功后,數(shù)據(jù)庫文件將存儲在由上下文指定的目錄里。注意:context入?yún)㈩愋蜑閛hos.app.Context,注意不要使用slice.getContext()來獲取context,請直接傳入slice,否則會出現(xiàn)找不到類的報錯。
總結
此文章用較小的篇幅講解了最基本的HarmonyOS中關系型數(shù)據(jù)庫和對象型數(shù)據(jù)庫的使用,使讀者能夠快速理解和上手相關的知識和操作,當讀者上手了這篇文章時,再去看其他更全更深層次的知識,相信會更加容易讀懂和上手。
??想了解更多內容,請訪問:??
??和華為官方合作共建的鴻蒙技術社區(qū)??
??https://ost.??
新聞標題:HarmonyOS—十分鐘教會數(shù)據(jù)庫快速上手
本文地址:http://m.5511xx.com/article/cojphgi.html


咨詢
建站咨詢
