import rdb from '@ohos.data.relationalStore'; import type common from '@ohos.app.ability.common'; import { BusinessError } from '@kit.BasicServicesKit';
const STORE_CONFIG: rdb.StoreConfig = { name: 'shop.db', securityLevel: rdb.SecurityLevel.S2 }; const SQL_CREATE_TABLE = 'CREATE TABLE IF NOT EXISTS goods(id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT NOT NULL)'; const TABLE_NAME = 'goods';
export class GoodsItemType { id: number = 0 name:string = ''
constructor(name: string) { this.name = name; } }
export class GoodsRdb { public table: rdb.RdbStore | undefined = undefined;
public async initRdbStore(context: common.Context): Promise { console.log('init rdbStore begin');
if (this.table) return
try {
this.table = await rdb.getRdbStore(context, STORE_CONFIG);
console.log('getRdbStore succeed');
// 创建数据库表
await this.table.executeSql(SQL_CREATE_TABLE)
console.log('create table succeed');
} catch (err) {
console.log(`getRdbStore failed, err: ${err}`);
return;
}
}
// 查询数据库 public async query(context:common.Context): Promise<Array> { console.log('query begin');
if (!this.table) await this.initRdbStore(context);
try {
const predicates = new rdb.RdbPredicates(TABLE_NAME);
const resultSet: rdb.ResultSet = await this.table!.query(predicates);
console.log('result is ' + JSON.stringify(resultSet.rowCount));
// 处理查询到的结果数组
const temp: Object[] = []
while (resultSet.goToNextRow()) {
// const id = resultSet.getLong(resultSet.getColumnIndex('id'));
// const name = resultSet.getString(resultSet.getColumnIndex('name'));
// const money = resultSet.getLong(resultSet.getColumnIndex('money'));
// console.info(`slj id=${id}, name=${name}, money=${money}`);
temp.push(resultSet.getRow())
}
resultSet.close();
return temp as GoodsItemType[];
} catch (err) {
console.log('query result error:' + JSON.stringify(err));
return [];
}
}
// 插入数据库 async insertData(context:common.Context, data: GoodsItemType): Promise { console.log('insert begin');
if (!this.table) await this.initRdbStore(context);
this.table!.insert(TABLE_NAME, { name: data.name, }, (err: BusinessError, rows: number) => {
if (err) {
console.log("Insert failed, err: " + err)
return
}
console.log(`insert done:${rows}`);
})
}
}