介绍
@ohos.data.rdb (关系型数据库)
关系型数据库(Relational Database,RDB)是一种基于关系模型来管理数据的数据库。关系型数据库基于SQLite组件提供了一套完整的对本地数据库进行管理的机制,对外提供了一系列的增、删、改、查等接口,也可以直接运行用户输入的SQL语句来满足复杂的场景需要。不支持Worker线程。
封装一个rdb的类测试
import { relationalStore, ValuesBucket } from '@kit.ArkData';
export class DBHelper{
// 操作数据库的实例
private store: relationalStore.RdbStore | null = null;
private tableName: string; // 数据库表的名称
private sqlCreate: string; // 创建数据库表的SQL语句
private securityLevel: relationalStore.SecurityLevel; // 数据库的安全等级
// 构造函数,初始化表名、创建语句和安全等级
constructor(tableName: string, sqlCreate: string, securityLevel: relationalStore.SecurityLevel) {
if (sqlCreate.includes(tableName)) {
this.tableName = tableName;
this.sqlCreate = sqlCreate;
this.securityLevel = securityLevel;
} else {
// 如果表名和建表语句内的表名不匹配,则抛出错误
console.error("The table name does not match the statement that created the table")
throw new Error("The table name does not match the statement that created the table");
}
}
// 获取数据库操作实例,如果已存在则直接返回,否则创建新的实例
async getStoreInstance() {
if (this.store) {
return this.store;
}
const store = await relationalStore.getRdbStore(getContext(), {
name: this.tableName + '.db', // 数据库名称
securityLevel: this.securityLevel // 安全等级
});
store.executeSql(this.sqlCreate); // 执行创建表的SQL语句
this.store = store; // 存储实例以便后续使用
return this.store; // 返回数据库操作实例
}
// 插入一条数据到数据库
async insertData<T extends ValuesBucket>(value: T) {
const store = await this.getStoreInstance();
return store.insert(this.tableName, value);
}
// 查询数据库中的数据量
async getTotal() {
const store = await this.getStoreInstance();
const predicates = new relationalStore.RdbPredicates(this.tableName);
const results = await store.query(predicates);
return results.rowCount <= 0 ? 0 : results.rowCount;
}
// 查询数据库列表,可以指定单个或多个ID,返回一个数组
async getTheList<T>(id?: number | number[]) {
const store = await this.getStoreInstance();
const predicates = new relationalStore.RdbPredicates(this.tableName);
if (typeof id === 'number') {
id = [id];
}
id !== undefined ? predicates.in("id", id) : predicates.orderByDesc("id");
const results = await store.query(predicates);
const list: T[] = [];
while (results.goToNextRow()) {
list.push(results.getRow() as T);
}
return list;
}
// 更新数据库中的数据
async upData<T extends ValuesBucket>(id: number, val: T) {
const store = await this.getStoreInstance();
const predicates = new relationalStore.RdbPredicates(this.tableName);
predicates.equalTo("id", id);
return store.update(val, predicates);
}
// 删除数据库中的数据
async delData(id: number) {
const store = await this.getStoreInstance();
const predicates = new relationalStore.RdbPredicates(this.tableName);
predicates.equalTo("id", id);
return store.delete(predicates);
}
}
测试代码
import { DBHelper } from './DBHelper'
import { relationalStore, ValuesBucket } from '@kit.ArkData'
import { promptAction } from '@kit.ArkUI'
export interface user extends ValuesBucket{
id:number|null,
name:string,
password:string,
}
let tableName='user'
let sqlCreate=`CREATE TABLE IF NOT EXISTS user
(id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
password TEXT NOT NULL
)`
let level=relationalStore.SecurityLevel.S1
export const db=new DBHelper(tableName,sqlCreate,level)
export const createTable=()=>{
const db=new DBHelper(tableName,sqlCreate,level)
console.log(`db:${JSON.stringify(db)}`)
}
export const insertData= async ()=>{
const db=new DBHelper(tableName,sqlCreate,level)
const u:user= {
name: 'tom',
password: '12345'
} as user
const res=await db.insertData(u)
if(res>0)
promptAction.showDialog({message:'插入成功'})
else
promptAction.showDialog({message:'插入失败'})
}
export const getAll= async ()=>{
const db=new DBHelper(tableName,sqlCreate,level)
const list=await db.getTheList<user>()
promptAction.showDialog({message:`all data:${JSON.stringify(list)}`})
}
export const selectById= async (id:number)=>{
const db=new DBHelper(tableName,sqlCreate,level)
const res = await db.getTheList<user>(id)
if(res.length!=0){
promptAction.showDialog({message:`查找成功:${
JSON.stringify(res)
}`})
}else {
promptAction.showDialog({message:'查找失败'})
}
}
export const deleteById= async (id:number)=>{
const db=new DBHelper(tableName,sqlCreate,level)
const res = await db.delData(id)
if(res===0){
promptAction.showDialog({message:`查找失败`})
}else {
promptAction.showDialog({message:'删除成功'})
}
}
测试页面
import { DBHelper } from '../common/DBHelper'
import { createTable, db, deleteById, getAll, insertData, selectById } from '../common/DBTest'
import { BusinessError } from '@kit.BasicServicesKit'
import { promptAction } from '@kit.ArkUI'
@Entry
@Component
struct DbTest {
build() {
Column(){
Button('create table')
.onClick(()=>{
createTable()
})
Button('insert data')
.onClick(()=>{
[1,2,3,4,5,6].forEach(item=>{
insertData()
})
})
Button('list data')
.onClick(()=>{
getAll()
})
Button('select by id')
.onClick(()=>{
selectById(1)
})
Button('delete by id')
.onClick(()=>{
deleteById(1)
})
Button('delete de by name')
.onClick(async ()=>{
const d=await db.getStoreInstance()
let sql=`drop table user`
d.executeSql(sql,(err:BusinessError,data)=>{
if(err!=undefined){
promptAction.showDialog({message:`删除失败`})
}else {
promptAction.showDialog({message:`删除成功`})
}
})
})
}
}
}