HarmonyOS 鸿蒙Next 关系型数据库获取的数据是根据id排序并非插入的顺序
HarmonyOS 鸿蒙Next 关系型数据库获取的数据是根据id排序并非插入的顺序
调用QueryData获取数据库全部数据时发现数据的顺序是根据id排的,怎么使获取的数据根据插入的顺序排?
//创建数据库及相关表
import { relationalStore, ValuesBucket } from "@kit.ArkData";
import { BusinessError } from "@kit.BasicServicesKit";
import { User } from '../db/User'
import { promptAction } from "@kit.ArkUI";
export default class Rdb{
rdbStore: relationalStore.RdbStore| null = null;
context:Context = getContext();
storeName: string = 'user'
constructor()
{
// 数据库配置
const STORE_CONFIG:relationalStore.StoreConfig = {
name:this.storeName,
securityLevel: relationalStore.SecurityLevel.S1,
};
// 获取数据库Store
relationalStore.getRdbStore(this.context, STORE_CONFIG, (err: BusinessError, rdbStore: relationalStore.RdbStore) => {
this.rdbStore = rdbStore;
if (err) {
console.error(`UserPage Get RdbStore failed, code is ${err.code},message is ${err.message}`);
return;
}
console.info(`UserPage Get ${this.storeName} RdbStore successfully.`);
})
}
CreateTable()
{
//建表语句 STUDENT为表名
const SQL_CREATE_TABLE = 'CREATE TABLE IF NOT EXISTS STUDENT (ID INTEGER PRIMARY KEY AUTOINCREMENT,NAME TEXT,SEX TEXT,AGE INTEGER,TEL TEXT)';
if(this.rdbStore !== null){
this.rdbStore.executeSql(SQL_CREATE_TABLE);
console.info(`UserPage CreateTable successfully.`);
}
}
InsertData(user:User)
{
// 插入数据TEXT
const valueBucket: ValuesBucket = {
"id": user.id,
"name": user.name,
"sex": user.sex,
"age": user.age,
"tel": user.tel
};
if(this.rdbStore!==null){
this.rdbStore.insert('STUDENT', valueBucket, (err, rowId) => {
if (err) {
console.error(`UserPage Failed to insert data. Code:${err.code}, message:${err.message}`);
return;
}
promptAction.showToast({
message: '添加用户成功!',
duration: 2000
});
console.info(`UserPage Succeeded in inserting data. rowId:${rowId}`);
})
}
}
DeleteData(name :string)
{
let predicates = new relationalStore.RdbPredicates("STUDENT");
predicates.equalTo("name", name);
if(this.rdbStore != undefined) {
(this.rdbStore as relationalStore.RdbStore).delete(predicates, (err, rows) => {
if (err) {
console.error(`UserPage Delete failed, code is ${err.code},message is ${err.message}`);
return;
}
console.info(`UserPage Delete rows: ${rows}`);
})
}
}
UpdateData(user:User)
{
const valueBucket: ValuesBucket = {
"id": user.id,
"name": user.name,
"sex": user.sex,
"age": user.age,
"tel": user.tel
};
let predicates = new relationalStore.RdbPredicates("EMPLOYEE");
predicates.equalTo("name", user.name);
if(this.rdbStore != undefined) {
(this.rdbStore as relationalStore.RdbStore).update(valueBucket, predicates, relationalStore.ConflictResolution.ON_CONFLICT_REPLACE, (err, rows) => {
if (err) {
console.error(`UserPage Updated failed, code is ${err.code},message is ${err.message}`);
return;
}
promptAction.showToast({
message: '成功!',
duration: 2000
});
console.info(`UserPage Updated row count: ${rows}`);
})
}
}
QueryData(callback:Callback<string>)
{
// 配置谓词
let predicates = new relationalStore.RdbPredicates("STUDENT");
let jsonData:Array<ValuesBucket> = new Array<ValuesBucket>();
if(this.rdbStore){
this.rdbStore.query(predicates, ["id", 'name','sex', 'age', 'tel'], (err, resultSet) => {
if (err) {
promptAction.showToast({
message: '失败!',
duration: 2000
});
console.error(`UserPage Failed to query data. Code:${err.code}, message:${err.message}`);
return;
}
console.info(`UserPage ResultSet column names: ${resultSet.columnNames}, row count: ${resultSet.rowCount}`);
if(resultSet.rowCount == -1){
console.info("rowCount=-1")
}
// resultSet是一个数据集合的游标,默认指向第-1个记录,有效的数据从0开始。
while (resultSet.goToNextRow()) {
const id = resultSet.getLong(resultSet.getColumnIndex("id"));
const name = resultSet.getString(resultSet.getColumnIndex("name"));
const sex = resultSet.getString(resultSet.getColumnIndex("sex"))
const age = resultSet.getLong(resultSet.getColumnIndex("age"));
const tel = resultSet.getDouble(resultSet.getColumnIndex("tel"));
console.info(`UserPage id=${id}, name=${name}, age=${age}, tel=${tel}`);
const valueBucket: ValuesBucket = {
"id": id,
"name": name,
"sex": sex,
"age": age,
"tel": tel
};
jsonData.unshift(valueBucket)
}
// 释放数据集的内存
resultSet.close();
// console.info("JSON: " + JSON.stringify(jsonData))
callback(JSON.stringify(jsonData))
})
}
}
QueryByName(name:string,callback:Callback<string>){
let predicates = new relationalStore.RdbPredicates("STUDENT");
let jsonData:Array<ValuesBucket> = new Array<ValuesBucket>();
predicates.equalTo("NAME", name);
if(this.rdbStore) {
this.rdbStore.query(predicates, ["id", 'name','sex', 'age', 'tel']).then((resultSet: relationalStore.ResultSet) => {
console.info(`ResultSet column names: ${resultSet.columnNames}, column count: ${resultSet.columnCount}`);
// resultSet是一个数据集合的游标,默认指向第-1个记录,有效的数据从0开始。
while (resultSet.goToNextRow()) {
const id = resultSet.getLong(resultSet.getColumnIndex("id"));
const name = resultSet.getString(resultSet.getColumnIndex("name"));
const sex = resultSet.getString(resultSet.getColumnIndex("sex"))
const age = resultSet.getLong(resultSet.getColumnIndex("age"));
const tel = resultSet.getDouble(resultSet.getColumnIndex("tel"));
const valueBucket: ValuesBucket = {
"id": id,
"name": name,
"sex": sex,
"age": age,
"tel": tel
};
jsonData.push(valueBucket)
}
// 释放数据集的内存,若不释放可能会引起fd泄露与内存泄露
resultSet.close();
callback(JSON.stringify(jsonData))
}).catch((err: BusinessError) => {
console.error(`Query failed, code is ${err.code},message is ${err.message}`);
})
}
}
}
-- 按照某个字段升序排序
SELECT * FROM table_name ORDER BY column_name ASC;
-- 按照某个字段降序排序
SELECT * FROM table_name ORDER BY column_name DESC;
或者你直接用时间戳做id?
我把id的类型改成字符串,数据库就不按id大小排了,就是类型转换麻烦点,现在只能暂时先这样弄了
在HarmonyOS鸿蒙Next系统中,关系型数据库(假设您使用的是SQLite或类似数据库)返回的数据默认是按照查询条件中的排序规则来排序的。如果您发现获取的数据是根据ID排序而非插入顺序,这通常是因为在查询时没有指定排序方式,而数据库内部可能默认按主键(通常是ID)排序返回结果。
要解决这个问题,您可以在SQL查询中明确指定排序规则。例如,如果您希望按照插入顺序获取数据,而您的表中有一个时间戳字段(如created_at
)或其他能反映插入顺序的字段,您可以在SELECT语句中添加ORDER BY
子句来指定排序字段。
示例SQL查询:
SELECT * FROM your_table_name ORDER BY created_at ASC;
这里created_at ASC
表示按照created_at
字段的升序排列,这通常可以反映插入顺序(假设每次插入都会记录当前时间戳)。
如果您没有这样的字段,而确实需要保持插入顺序,您可能需要考虑在应用层面维护一个插入顺序的索引或列表。
如果问题依旧没法解决请联系官网客服,官网地址是:https://www.itying.com/category-93-b0.html