• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1/*
2 * Copyright (c) 2025 Huawei Device Co., Ltd.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 *     http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16import { relationalStore, ValuesBucket } from '@kit.ArkData';
17import { taskpool } from '@kit.ArkTS';
18
19@Concurrent
20async function create(context: Context) {
21  const CONFIG: relationalStore.StoreConfig = {
22    name: 'Store.db',
23    securityLevel: relationalStore.SecurityLevel.S1,
24  };
25
26  // 默认数据库文件路径为 context.databaseDir + rdb + StoreConfig.name
27  let store: relationalStore.RdbStore = await relationalStore.getRdbStore(context, CONFIG);
28  console.info(`Create Store.db successfully!`);
29
30  // 创建表
31  const CREATE_TABLE_SQL = 'CREATE TABLE IF NOT EXISTS test (' +
32    'id INTEGER PRIMARY KEY AUTOINCREMENT, ' +
33    'name TEXT NOT NULL, ' +
34    'age INTEGER, ' +
35    'salary REAL, ' +
36    'blobType BLOB)';
37  await store.executeSql(CREATE_TABLE_SQL);
38  console.info(`Create table test successfully!`);
39}
40
41@Concurrent
42async function insert(context: Context, valueBucketArray: Array<relationalStore.ValuesBucket>) {
43  const CONFIG: relationalStore.StoreConfig = {
44    name: 'Store.db',
45    securityLevel: relationalStore.SecurityLevel.S1,
46  };
47
48  // 默认数据库文件路径为 context.databaseDir + rdb + StoreConfig.name
49  let store: relationalStore.RdbStore = await relationalStore.getRdbStore(context, CONFIG);
50  console.info(`Create Store.db successfully!`);
51
52  // 数据插入
53  await store.batchInsert('test', valueBucketArray as Object as Array<relationalStore.ValuesBucket>);
54}
55
56@Concurrent
57async function query(context: Context): Promise<Array<relationalStore.ValuesBucket>> {
58  const CONFIG: relationalStore.StoreConfig = {
59    name: 'Store.db',
60    securityLevel: relationalStore.SecurityLevel.S1,
61  };
62
63  // 默认数据库文件路径为 context.databaseDir + rdb + StoreConfig.name
64  let store: relationalStore.RdbStore = await relationalStore.getRdbStore(context, CONFIG);
65  console.info(`Create Store.db successfully!`);
66
67  // 获取结果集
68  let predicates: relationalStore.RdbPredicates = new relationalStore.RdbPredicates('test');
69  let resultSet = await store.query(predicates); // 查询所有数据
70  console.info(`Query data successfully! row count:${resultSet.rowCount}`);
71  let index = 0;
72  let result = new Array<relationalStore.ValuesBucket>(resultSet.rowCount)
73  resultSet.goToFirstRow()
74  do {
75    result[index++] = resultSet.getRow();
76  } while (resultSet.goToNextRow());
77  resultSet.close();
78  return result;
79}
80
81@Concurrent
82async function clear(context: Context) {
83  const CONFIG: relationalStore.StoreConfig = {
84    name: 'Store.db',
85    securityLevel: relationalStore.SecurityLevel.S1,
86  };
87
88  // 默认数据库文件路径为 context.databaseDir + rdb + StoreConfig.name
89  await relationalStore.deleteRdbStore(context, CONFIG);
90  console.info(`Delete Store.db successfully!`);
91}
92
93@Entry
94@Component
95struct Index {
96  @State message: string = 'Hello World';
97
98  build() {
99    RelativeContainer() {
100      Text(this.message)
101        .id('HelloWorld')
102        .fontSize(50)
103        .fontWeight(FontWeight.Bold)
104        .alignRules({
105          center: { anchor: '__container__', align: VerticalAlign.Center },
106          middle: { anchor: '__container__', align: HorizontalAlign.Center }
107        })
108        .onClick(async () => {
109          let context = getContext(this);
110
111          // 数据准备
112          const count = 5
113          let valueBucketArray = new Array<relationalStore.ValuesBucket>(count);
114          for (let i = 0; i < count; i++) {
115            let v: relationalStore.ValuesBucket = {
116              id: i,
117              name: 'zhangsan' + i,
118              age: 20,
119              salary: 5000 + 50 * i
120            };
121            valueBucketArray[i] = v;
122          }
123          await taskpool.execute(create, context);
124          await taskpool.execute(insert, context, valueBucketArray);
125          let index = 0;
126          let ret = await taskpool.execute(query, context) as Array<relationalStore.ValuesBucket>;
127          for (let v of ret) {
128            console.info(`Row[${index}].id = ${v.id}`)
129            console.info(`Row[${index}].name = ${v.name}`)
130            console.info(`Row[${index}].age = ${v.age}`)
131            console.info(`Row[${index}].salary = ${v.salary}`)
132            index++
133          };
134          await taskpool.execute(clear, context);
135          this.message = 'success';
136        })
137    }
138    .height('100%')
139    .width('100%')
140  }
141}
142