修改entry/src/main/ets/entryability目录下的EntryAbility.ts文件:
在
export default class EntryAbility extends UIAbility {onCreate(want, launchParam) {hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onCreate');
之后添加:
const config={ name:'person.db', //数据库文件名 SecurityLevel:relationalStore.SecurityLevel.S1 } const sql='create table if not exists account(id int primary key,username varchar not null)' relationalStore.getRdbStore(this.context,config,(err,rdbStore)=>{if (err) {console.log('连接失败') }console.log('连接成功')rdbStore.executeSql(sql)globalThis.rdbStore=rdbStore })
在
import window from '@ohos.window';
之后添加(如果输入上边代码后没有自动添加的话):
import relationalStore from '@ohos.data.relationalStore'; import securityLabel from '@ohos.file.securityLabel';
修改entry/src/main/ets/pages路径下的index.ets文件:
import relationalStore from '@ohos.data.relationalStore' @Entry @Component struct Index {@State message: string = 'Hello World'rdbStore:relationalStore.RdbStore=globalThis.rdbStorebuild() {Row() {Column() {Text(this.message).fontSize(50).fontWeight(FontWeight.Bold)Text('增加').onClick(()=>{// insert into account values(1,'zhangsan')let data={id:1,username:'zhangsan'}this.rdbStore.insert('account',data,(err,rowId)=>{if (err) {console.log('添加失败')}console.log(rowId.toString()+'添加成功')})})Text('增加') //第二条数据,可直接复制上边增加的代码.onClick(()=>{// insert into account values(2,'wangwu')let data={id:2,username:'wangwu'}this.rdbStore.insert('account',data,(err,rowId)=>{if (err) {console.log('添加失败')}console.log(rowId.toString()+'添加成功')})})Text('更新').onClick(()=>{//update account set username='lisi' where id=1let predicates=new relationalStore.RdbPredicates('account')predicates.equalTo('id',1)let data={username:'lisi'}this.rdbStore.update(data,predicates,(err,rows)=>{if (err) {console.log('sql语句错误,更新失败')}// rows输出值为0,说明没有更新;row为1,说明已更新console.log(rows.toString()+'更新成功')})})Text('删除').onClick(()=>{//delete from account where id=1let predicates=new relationalStore.RdbPredicates('account')predicates.equalTo('id',1)this.rdbStore.delete(predicates,(err,rows)=>{if (err) {console.log('sql语句错误,删除失败')}console.log(rows.toString()+'删除成功')})})Text('获取').onClick(()=>{//select id,username from account where id=1let predicates=new relationalStore.RdbPredicates('account')// predicates.equalTo('id',1) //查询多条时注释掉this.rdbStore.query(predicates,['id','username'],(err,resultSet)=>{//resultSet.isAtLastRow方法 用于判断是不是箭头在最后一行,如果在最后一行返回true,否则返回falseif (!resultSet.isAtLastRow) {resultSet.goToNextRow() //将箭头指针指向下一行//getColumnIndex 是获取指针指向那一行的哪个字段,getLong是获取字段相应的数据类型console.log(resultSet.getLong(resultSet.getColumnIndex('id')).toString()+'获取成功')console.log(resultSet.getString(resultSet.getColumnIndex('username'))+'获取成功')}})})}.width('100%')}.height('100%')} }
实际效果图: