建立一个测试页面
对象结构体
// ValuesBucket 数据库支持的类型
interface NoteItem extends ValuesBucket {
id: number | null // 新增时设置 id 为空值 null,用于自增 id
title: string
content: string
date_added: number
}
获得数据库管理对象
store: relationalStore.RdbStore | null = null
建表语句
sqlCreate: string = `CREATE TABLE IF NOT EXISTS privacy_note (
id INTEGER PRIMARY KEY AUTOINCREMENT,
title TEXT NOT NULL,
content TEXT NOT NULL,
date_added INTEGER NOT NULL
)`
获得数据库管理对象函数
`
async getStoreInstance() {
if (this.store) {
return this.store
}
// 获取操作数据库的管理对象(如果数据库文件不存在,会自动创建数据库文件)
this.store = await relationalStore.getRdbStore(getContext(), {
name: 'heima.db', // 数据库文件名
securityLevel: relationalStore.SecurityLevel.S1, // 数据库安全级别
})
// 执行创建表的语句 execute 执行
this.store.executeSql(this.sqlCreate)
// 返回 store 对象
return this.store
}
创建数据库文件测试按钮
Button('创建数据库文件')
.onClick(async () => {
// 获取操作数据库的管理对象(如果数据库文件不存在,会自动创建数据库文件)
const store = await relationalStore.getRdbStore(getContext(), {
name: 'heima.db', // 数据库文件名
securityLevel: relationalStore.SecurityLevel.S1, // 数据库安全级别
})
// 执行创建表的语句 execute 执行
store.executeSql(this.sqlCreate)
AlertDialog.show({ message: '创建成功' })
})
查询数据库表字段测试按钮
Button('查询数据库表的字段')
.onClick(async () => {
// 获取操作数据库的对象
const store = await this.getStoreInstance()
// 谓词(条件),谓词类需要 new 实例化,传入表名 privacy_note
const predicates = new relationalStore.RdbPredicates('privacy_note')
// query 查询,传入必传参数 谓词
const resultSet = await store.query(predicates)
AlertDialog.show({ message: '数据库的字段名:' + resultSet.columnNames })
})
新建一条数据测试按钮
Button('新建一条数据')
.onClick(async () => {
// 获取操作数据库的对象
const store = await this.getStoreInstance()
// 添加一条数据
const id = await store.insert(this.tableName, {
id: null, // 新增时设置 id 为空值 null,用于自增 id
title: '关键的问题',
content: '111',
date_added: Date.now()
} as NoteItem)
AlertDialog.show({ message: '新增数组成功,数据的id为:' + id })
// 批量添加,传入数组
// store.batchInsert(表名, 数组)
})