之前的文章介绍了Ability,这里附上自己测试的demo
想要创建关系数据库可以参考官方示例,如果你已经有了MainAbility与MyAbilitySlice,那么只需要创建一个DataAbility即可。
创建Data Ability
FIle > new > Data Ability,DS(DevEco Studio)会自动创建Data Ability,并且在config.json中注册完成,请注意查看config.json中的uri,作为下面中的uri的替换。
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.orm.OrmContext;
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;
/**
* Data Ability 数据存储 关系型数据库
*
* @author yilei.liu
* 2021.8.24
*/
public class DataAbility extends Ability {
private static final HiLogLabel LABEL_LOG = new HiLogLabel(3, 0xD001100, "Demo");
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";
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 static final int DB_VERSION = 1;
private StoreConfig config = StoreConfig.newDefaultConfig(DB_NAME);
private RdbStore rdbStore;
// 创建关系型数据库
private RdbOpenCallback rdbOpenCallback = new RdbOpenCallback() {
// 这个字符串少个空格都可能会报错,注意格式,这里设计真不太行,
// 为什么不使用类似greenDAO的方式呢?
@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 rdbStore, int i, int i1) {
}
};
@Override
public void onStart(Intent intent) {
super.onStart(intent);
HiLog.info(LABEL_LOG, "DataAbility onStart");
// 初始化数据库连接
DatabaseHelper databaseHelper = new DatabaseHelper(this);
rdbStore = databaseHelper.getRdbStore(config, DB_VERSION, rdbOpenCallback, null);
}
// 重写操作方法
@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, "查询结果为空");
}
return resultSet;
}
@Override
public int insert(Uri uri, ValuesBucket value) {
HiLog.info(LABEL_LOG, "DataAbility insert");
String path = uri.getLastPath();
if (!"person".equals(path)) {
HiLog.info(LABEL_LOG, "没有符合的路径uri");
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);
return index;
}
@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;
}
@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;
}
}
在MyAbilitySlice中定义数据库操作的函数,当然,如果真的项目使用,当然要另外封装类
import com.example.demo.ResourceTable;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.ability.DataAbilityHelper;
import ohos.aafwk.ability.DataAbilityRemoteException;
import ohos.aafwk.content.Intent;
import ohos.agp.components.Button;
import ohos.data.dataability.DataAbilityPredicates;
import ohos.data.rdb.ValuesBucket;
import ohos.data.resultset.ResultSet;
import ohos.hiviewdfx.HiLog;
import ohos.hiviewdfx.HiLogLabel;
import ohos.utils.net.Uri;
/**
* 主Ability的Slice
*
* @author yilei.liu
* 2021.8.24
*/
public class MainAbilitySlice extends AbilitySlice {
private static final HiLogLabel LABEL_LOG = new HiLogLabel(3, 0xD001100, "MainAbilitySlice");
private DataAbilityHelper dataAbilityHelper;
private static final String BASE_URI = "dataability:///com.example.demo.DataAbility";
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";
@Override
public void onStart(Intent intent) {
super.onStart(intent);
super.setUIContent(ResourceTable.Layout_ability_main);
Button button = (Button) findComponentById(ResourceTable.Id_enter_newAbilitySlice);
dataAbilityHelper = DataAbilityHelper.creator(this);
button.setClickedListener(listener -> {
// insert(1, "明日香", "女", 28);
// query();
// update();
query();
});
}
@Override
public void onActive() {
super.onActive();
}
@Override
public void onForeground(Intent intent) {
super.onForeground(intent);
}
// 数据库操作方法
private void query() {
String[] columns = new String[]{DB_COLUMN_PERSON_ID, DB_COLUMN_NAME, DB_COLUMN_GENDER, DB_COLUMN_AGE};
// 查询条件
DataAbilityPredicates predicates = new DataAbilityPredicates();
// 年龄在15与40之间
predicates.between(DB_COLUMN_AGE, 15, 40);
try {
ResultSet resultSet = dataAbilityHelper.query(Uri.parse(BASE_URI + DATA_PATH), columns, predicates);
if (resultSet == null || resultSet.getRowCount() == 0) {
HiLog.info(LABEL_LOG, "未查询到");
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));
System.out.println("查询到:id是" + id + "姓名是:" + name + "性别为:" + gender + "年龄为:" + age);
} while (resultSet.goToNextRow());
} catch (DataAbilityRemoteException | IllegalStateException exception) {
HiLog.error(LABEL_LOG, "查询出错");
}
}
private 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);
try {
if (dataAbilityHelper.insert(Uri.parse(BASE_URI + DATA_PATH), valuesBucket) != -1) {
HiLog.info(LABEL_LOG, "插入成功");
}
} catch (DataAbilityRemoteException | IllegalStateException exception) {
HiLog.error(LABEL_LOG, "插入出错");
}
}
private void update() {
DataAbilityPredicates predicates = new DataAbilityPredicates();
predicates.equalTo(DB_COLUMN_PERSON_ID, 1);
ValuesBucket valuesBucket = new ValuesBucket();
valuesBucket.putString(DB_COLUMN_NAME, "绫波丽");
valuesBucket.putInteger(DB_COLUMN_AGE, 27);
try {
if (dataAbilityHelper.update(Uri.parse(BASE_URI + DATA_PATH), valuesBucket, predicates) != -1) {
HiLog.info(LABEL_LOG, "更新成功");
}
} catch (DataAbilityRemoteException | IllegalStateException exception) {
HiLog.error(LABEL_LOG, "更新出错啦");
}
}
private void delete(int id) {
DataAbilityPredicates predicates = new DataAbilityPredicates()
.equalTo(DB_COLUMN_PERSON_ID, 2);
try {
if (dataAbilityHelper.delete(Uri.parse(BASE_URI + DATA_PATH), predicates) != -1) {
HiLog.info(LABEL_LOG, "删除成功");
}
} catch (DataAbilityRemoteException | IllegalStateException exception) {
HiLog.error(LABEL_LOG, "删除出错");
}
}
}
结果