HarmonyOS 鸿蒙Next rdb数据库querySql使用bindArgs问题
HarmonyOS 鸿蒙Next rdb数据库querySql使用bindArgs问题
2.rdb数据,query不能够多表查询,RdbPredicates这个只能单表,有无多表查询的方法
1 占位符不支持占位数据表名称,可以使用一个变量代替占位表名的位置
[@State](/user/State) tab_name: string = ' '
...
this.tab_name='EMPLOYEE';
(store as relationalStore.RdbStore).querySql(` SELECT * FROM ${tab_name} `).then((resultSet: relationalStore.ResultSet) => {}
可以进行多表查询
可以使用join或者如下查询语句
(store as relationalStore.RdbStore).querySql(" SELECT * FROM EMPLOYEE,EMPLOYEE2 WHERE EMPLOYEE.NAME=EMPLOYEE2.NAME2").then((resultSet: relationalStore.ResultSet) => { RdbPredicates表示关系型数据库(RDB)的谓词。该类确定RDB中条件表达式的值是true还是false。没有多表查询
可以通过querySql接口直接执行自定义SQL语句,
参考链接:https://developer.huawei.com/consumer/cn/doc/harmonyos-references-V13/js-apis-data-rdb-V13#querysql8
通过querySql执行下面的语句,可以成功查询到数据
"SELECT a.ID id1,b.ID id2,a.NAME name1,b.NAME name2,a.AGE age1,b.AGE age2 FROM EMPLOYEE a ,EMPLOYEE2 b WHERE a.ID=b.ID"
demo:
import fs from '[@ohos](/user/ohos).file.fs';
import buffer from '[@ohos](/user/ohos).buffer';
import { ValuesBucket } from '[@ohos](/user/ohos).data.ValuesBucket';
import common from '[@ohos](/user/ohos).app.ability.common';
import relationalStore from '[@ohos](/user/ohos).data.relationalStore'; // 导入模块
import { BusinessError } from '[@ohos](/user/ohos).base';
import hilog from '[@ohos](/user/ohos).hilog';
import promptAction from '[@ohos](/user/ohos).promptAction';
import File from '[@system](/user/system).file';
let store: relationalStore.RdbStore | undefined = undefined;
let predicates = new relationalStore.RdbPredicates("EMPLOYEE");
const table_name: string = 'EMPLOYEE'
// 建表Sql语句1
const SQL_CREATE_TABLE =
`CREATE TABLE IF NOT EXISTS ${table_name} (` +
'ID INTEGER PRIMARY KEY AUTOINCREMENT, ' +
'NAME TEXT NOT NULL, AGE INTEGER, ' +
'CODES BLOB' +
')';
// 建表Sql语句2
const SQL_CREATE_TABLE2 =
`CREATE TABLE IF NOT EXISTS EMPLOYEE2 (` +
'ID INTEGER PRIMARY KEY AUTOINCREMENT, ' +
'NAME TEXT NOT NULL, AGE INTEGER, ' +
'CODES BLOB' +
')';
[@Entry](/user/Entry)
[@Component](/user/Component)
struct Index {
[@State](/user/State) message: string = 'Hello World';
[@State](/user/State) database_version: number = 0;
[@State](/user/State) database_name: string = '未创建';
[@State](/user/State) database_flag: number = -1;
[@State](/user/State) create_flag: number = -1
[@State](/user/State) table_name1: string = 'EMPLOYEE'
[@State](/user/State) table_name2: string = 'EMPLOYEE2'
context = getContext(this) as common.UIAbilityContext;
build() {
Column() {
//1、数据库创建
Row() {
Text(`数据库名:${this.database_name}`)
.textAlign(TextAlign.Start)
.fontSize(12)//.border({ width: 1 })
.padding(10)
.width('50%')
}
.width('90%')
.border({ width: 1 })
//2、建表
Row() {
if (this.create_flag === 1) {
Text(`表名1:${this.table_name1}`)
.textAlign(TextAlign.Start)
.fontSize(12)
.padding(10)
.width('50%')
} else {
Text(`表名:未建表`)
.textAlign(TextAlign.Start)
.fontSize(12)
.padding(10)
.width('50%')
}
}
.width('90%')
.border({ width: 1 })
//2、建表2
Row() {
if (this.create_flag === 1) {
Text(`表名2:${this.table_name2}`)
.textAlign(TextAlign.Start)
.fontSize(12)
.padding(10)
.width('50%')
} else {
Text(`表名:未建表`)
.textAlign(TextAlign.Start)
.fontSize(12)
.padding(10)
.width('50%')
}
}
.width('90%')
.border({ width: 1 })
Button('1、创建数据库')
.onClick(() => {
if (this.database_flag === -1) {
this.getDataStore()
} else {
if (this.database_flag === 1) {
promptAction.showToast({
message: '数据库已创建'
});
}
}
})
Button('2、建表')
.onClick(() => {
if (this.database_flag === -1) {
promptAction.showToast({
message: '数据库未创建,请先创建数据库'
});
return;
}
this.createDatabase()
this.createDatabase2()
})
Button('3、插入数据')
.onClick(() => {
this.insertDate()
this.insertDate2()
})
Button('4、查询数据表')
.onClick(() => {
this.queryData3()
})
}
}
//获取store,创建数据库
getDataStore() {
//设置数据库基本配置信息
const STORE_CONFIG: relationalStore.StoreConfig = {
name: "RdbTest.db", // 数据库文件名
securityLevel: relationalStore.SecurityLevel.S1// 数据库安全级别
};
relationalStore.getRdbStore(this.context, STORE_CONFIG).then(async (rdbStore: relationalStore.RdbStore) => {
store = rdbStore; //操作关系型数据库
console.info('成功获取RdbStore:' + store)
this.database_name = STORE_CONFIG.name
this.database_flag = 1
}).catch((err: BusinessError) => {
console.error(`获取RdbStore失败, code is ${err.code},message is ${err.message}`);
})
}
//建表1
createDatabase() {
if (store != undefined) {
(store as relationalStore.RdbStore).executeSql(SQL_CREATE_TABLE, (err) => {
if (err) {
console.error(`数据表创建失败, code is ${err.code},message is ${err.message}`);
return;
}
console.info('数据表11111创建成功');
this.create_flag = 1
// 设置数据库版本
if (store != undefined) {
(store as relationalStore.RdbStore).version = 3;
// 获取数据库版本
console.info(`RdbStore version is ${store.version}`);
}
})
}
}
//建表2
createDatabase2() {
if (store != undefined) {
(store as relationalStore.RdbStore).executeSql(SQL_CREATE_TABLE2, (err) => {
if (err) {
console.error(`数据表创建失败, code is ${err.code},message is ${err.message}`);
return;
}
console.info('数据表2222创建成功');
this.create_flag = 1
// 设置数据库版本
if (store != undefined) {
// this.database_version=(store as relationalStore.RdbStore).version+1;
(store as relationalStore.RdbStore).version = 3;
// 获取数据库版本
console.info(`RdbStore version is ${store.version}`);
}
})
}
}
//插入数据
insertDate() {
//数据初始化
let value1 = 'Lisa';
let value2 = 18;
// 以下三种方式可用
const valueBucket1: ValuesBucket = {
'NAME': value1,
'AGE': value2,
};
if (store != undefined) {
(store as relationalStore.RdbStore).insert("EMPLOYEE", valueBucket1, (err: BusinessError, rowId: number) => {
if (err) {
console.error(`插入失败, code is ${err.code},message is ${err.message}`);
return;
}
console.info(`插入成功1111, rowId是:${rowId}`);
promptAction.showToast({
message: `插入成功1111`
});
})
}
}
//插入数据
insertDate2() {
//数据初始化
let value1 = 'XIAOHONG';
let value2 = 20;
// 以下三种方式可用
const valueBucket1: ValuesBucket = {
'NAME': value1,
'AGE': value2,
};
if (store != undefined) {
(store as relationalStore.RdbStore).insert("EMPLOYEE2", valueBucket1, (err: BusinessError, rowId: number) => {
if (err) {
console.error(`插入失败, code is ${err.code},message is ${err.message}`);
return;
}
console.info(`插入成功222, rowId是:${rowId}`);
promptAction.showToast({
message: `插入成功2222`
});
})
}
}
queryData3() {
if (store != undefined) {
(store as relationalStore.RdbStore).querySql("SELECT a.ID id1,b.ID id2,a.NAME name1,b.NAME name2,a.AGE age1,b.AGE age2 FROM EMPLOYEE a ,EMPLOYEE2 b WHERE a.ID=b.ID",
(err, resultSet) => {
if (err) {
console.error(`Query failed, code is ${err.code},message is ${err.message}`);
return;
}
console.info(`ResultSet column names: ${resultSet.columnNames}, column count: ${resultSet.columnCount}`);
console.log("返回的行数:" + resultSet.rowCount);
console.log("查询到列名:" + resultSet.columnNames);
console.log("返回的列数:" + resultSet.columnCount);
while (resultSet.goToNextRow()) {
const id1 = resultSet.getLong(resultSet.getColumnIndex("id1"));
const name1 = resultSet.getString(resultSet.getColumnIndex("name1"));
const age1 = resultSet.getLong(resultSet.getColumnIndex("age1"));
const id2 = resultSet.getLong(resultSet.getColumnIndex("id2"));
const name2 = resultSet.getString(resultSet.getColumnIndex("name2"));
const age2 = resultSet.getLong(resultSet.getColumnIndex("age2"));
console.info(`id=${id1}, name=${name1}, age=${age1}`);
console.info(`id2=${id2}, name2=${name2}, age2=${age2}`);
}
// 释放数据集的内存
resultSet.close();
})
}
}
}
更多关于HarmonyOS 鸿蒙Next rdb数据库querySql使用bindArgs问题的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html
在HarmonyOS鸿蒙Next的rdb数据库中,使用querySql
方法进行SQL查询时,bindArgs
参数用于绑定SQL语句中的占位符,以避免SQL注入攻击并提高查询效率。以下是关于bindArgs
使用的直接说明:
querySql
方法通常接收一个SQL语句和一个或多个绑定参数。SQL语句中的占位符使用?
表示。例如,SQL语句"SELECT * FROM table WHERE column = ?"
需要绑定一个参数来替换?
。
在调用querySql
时,bindArgs
参数应为一个数组,数组中的每个元素对应SQL语句中的一个占位符。数组元素的顺序应与SQL语句中占位符的顺序一致。例如:
String sql = "SELECT * FROM table WHERE column = ?";
Object[] bindArgs = { "value" };
ResultSet resultSet = rdbStore.querySql(sql, bindArgs);
在上述示例中,bindArgs
数组包含一个元素"value"
,它将替换SQL语句中的第一个(也是唯一一个)占位符?
。
请确保bindArgs
数组中的元素类型与SQL语句中占位符所期望的类型相匹配,以避免类型不匹配导致的错误。
如果问题依旧没法解决请联系官网客服,官网地址是:https://www.itying.com/category-93-b0.html