使用键值对数据库插入数据之后,无法从其中查询出数据,插入数据案例代码如下:
import { distributedKVStore } from '@kit.ArkData';
import { BusinessError } from '@kit.BasicServicesKit';
@Entry
@Component
struct KVStoreDemo {
kvStore: distributedKVStore.SingleKVStore | undefined = undefined;
async aboutToAppear(): Promise<void> {
const kvManagerConfig: distributedKVStore.KVManagerConfig = {
bundleName: 'com.example.myapplication0116',
context: this.getUIContext().getHostContext()!
};
let kvManager = distributedKVStore.createKVManager(kvManagerConfig);
const options: distributedKVStore.Options = {
securityLevel: distributedKVStore.SecurityLevel.S3,
kvStoreType: distributedKVStore.KVStoreType.SINGLE_VERSION
};
await kvManager.getKVStore('kvStore', options, (err: BusinessError, kvStore: distributedKVStore.SingleKVStore) => {
if (err) {
console.error(`Failed to get KVStore.code is ${err.code},message is ${err.message}`);
return;
}
this.kvStore = kvStore!;
});
this.kvStore?.put('testKey', 'testValue');
}
build() {
Column() {
Text('查询')
.fontSize(50)
.fontWeight(FontWeight.Medium)
.onClick(async () => {
try {
let value = await this.kvStore?.get('testKey');
console.info(`${value}`);
} catch (error) {
let err = error as BusinessError;
console.error(`code:${err.code};message:${err.message}`);
}
})
}
.height('100%')
.width('100%')
}
} 异步并发:Promise和async/await是标准的JS异步语法,提供异步并发能力。异步代码执行时会被挂起,稍后继续执行,确保同一时间只有一段代码在运行。
分布式键值数据库:分布式键值数据库为应用程序提供不同设备间数据库的分布式协同能力。通过调用分布式键值数据库各个接口,应用程序可将数据保存到分布式键值数据库中,并可对分布式键值数据库中的数据进行增加、删除、修改、查询、端端同步等操作。
基于分析结论,修改后的完整实例代码如下:
import { distributedKVStore } from '@kit.ArkData';
import { BusinessError } from '@kit.BasicServicesKit';
@Entry
@Component
struct KVStoreDemo {
kvStore: distributedKVStore.SingleKVStore | undefined = undefined;
async aboutToAppear(): Promise<void> {
const kvManagerConfig: distributedKVStore.KVManagerConfig = {
bundleName: 'com.example.myapplication',
context: this.getUIContext().getHostContext()!
};
let kvManager = distributedKVStore.createKVManager(kvManagerConfig);
const options: distributedKVStore.Options = {
securityLevel: distributedKVStore.SecurityLevel.S3,
kvStoreType: distributedKVStore.KVStoreType.SINGLE_VERSION
};
this.kvStore = await kvManager.getKVStore('kvStore', options);
this.kvStore?.put('testKey', 'testValue');
}
build() {
Column() {
Text('查询')
.fontSize(50)
.fontWeight(FontWeight.Medium)
.onClick(async () => {
try {
let value = await this.kvStore?.get('testKey');
console.info(`testKey --- ${value}`);
} catch (error) {
let err = error as BusinessError;
console.error(`code:${err.code};message:${err.message}`);
}
})
}
.height('100%')
.width('100%')
}
}