• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Persisting KV Store Data
2
3
4## When to Use
5
6The key-value (KV) database stores data in the form of KV pairs. You can use KV stores to store data organized in a simple model, for example, product names and prices or employee IDs and daily attendance. The simple data structure allows higher compatibility with different database versions and device types.
7
8
9## Constraints
10
11- For each record in a device KV store, the key cannot exceed 896 bytes and the value cannot exceed 4 MB.
12
13- For each record in a single KV store, the key cannot exceed 1 KB and the value cannot exceed 4 MB.
14
15- A maximum of 16 distributed KV stores can be opened simultaneously for an application.
16
17- Blocking operations, for example, modifying UI components, are not allowed in the KV store event callbacks.
18
19
20## Available APIs
21
22The following table lists the APIs used for KV data persistence. Most of the APIs are executed asynchronously, using a callback or promise to return the result. The following table uses the callback-based APIs as an example. For more information about the APIs, see [Distributed KV Store](../reference/apis-arkdata/js-apis-distributedKVStore.md).
23
24| API| Description|
25| -------- | -------- |
26| createKVManager(config: KVManagerConfig): KVManager | Creates a **KvManager** instance to manage database objects.|
27| getKVStore<T>(storeId: string, options: Options, callback: AsyncCallback<T>): void | Creates and obtains a KV store of the specified type.|
28| put(key: string, value: Uint8Array\|string\|number\|boolean, callback: AsyncCallback<void>): void | Adds a KV pair of the specified type to this KV store.|
29| get(key: string, callback: AsyncCallback<Uint8Array\|string\|boolean\|number>): void | Obtains the value of the specified key.|
30| delete(key: string, callback: AsyncCallback<void>): void | Deletes a KV pair based on the specified key.|
31
32
33## How to Develop
34
351. Create a **KvManager** instance to manage database objects.<br>Example:
36
37   Stage model:
38
39
40   ```js
41   // Import the module.
42   import distributedKVStore from '@ohos.data.distributedKVStore';
43
44   // Stage model
45   import window from '@ohos.window';
46   import UIAbility from '@ohos.app.ability.UIAbility';
47   import { BusinessError } from '@ohos.base';
48
49   let kvManager: distributedKVStore.KVManager | undefined = undefined;
50
51   export default class EntryAbility extends UIAbility {
52     onCreate() {
53       let context = this.context;
54       const kvManagerConfig: distributedKVStore.KVManagerConfig = {
55         context: context,
56         bundleName: 'com.example.datamanagertest'
57       };
58       try {
59         // Create a KVManager instance.
60         kvManager = distributedKVStore.createKVManager(kvManagerConfig);
61         console.info('Succeeded in creating KVManager.');
62         // Create and obtain the database.
63       } catch (e) {
64         let error = e as BusinessError;
65         console.error(`Failed to create KVManager. Code:${error.code},message:${error.message}`);
66       }
67     }
68   }
69   if (kvManager !== undefined) {
70      kvManager = kvManager as distributedKVStore.KVManager;
71     // Perform subsequent operations.
72     //...
73   }
74   ```
75
76   FA model:
77
78
79   ```js
80   // Import the module.
81   import distributedKVStore from '@ohos.data.distributedKVStore';
82
83   // FA model
84   import featureAbility from '@ohos.ability.featureAbility';
85
86   let kvManager: distributedKVStore.KVManager | undefined = undefined;
87   let context = featureAbility.getContext(); // Obtain the context.
88   const kvManagerConfig: distributedKVStore.KVManagerConfig = {
89     context: context,
90     bundleName: 'com.example.datamanagertest'
91   };
92   try {
93     kvManager = distributedKVStore.createKVManager(kvManagerConfig);
94     console.info('Succeeded in creating KVManager.');
95     // Create and obtain the database.
96   } catch (e) {
97      let error = e as BusinessError;
98      console.error(`Failed to create KVManager. Code:${error.code},message:${error.message}`);
99   }
100   if (kvManager !== undefined) {
101     kvManager = kvManager as distributedKVStore.KVManager;
102     // Perform subsequent operations.
103     //...
104   }
105
106   ```
107
1082. Create and obtain a KV store.<br>Example:
109
110   ```js
111   let kvStore: distributedKVStore.SingleKVStore | undefined = undefined;
112   try {
113     const options: distributedKVStore.Options = {
114       createIfMissing: true,
115       encrypt: false,
116       backup: false,
117       autoSync: false,
118       // If kvStoreType is left empty, a device KV store is created by default.
119       kvStoreType: distributedKVStore.KVStoreType.SINGLE_VERSION,
120       // Device KV store: kvStoreType: distributedKVStore.KVStoreType.DEVICE_COLLABORATION,
121       securityLevel: distributedKVStore.SecurityLevel.S1
122     };
123     kvManager.getKVStore<distributedKVStore.SingleKVStore>('storeId', options, (err, store: distributedKVStore.SingleKVStore) => {
124       if (err) {
125         console.error(`Failed to get KVStore: Code:${err.code},message:${err.message}`);
126         return;
127       }
128       console.info('Succeeded in getting KVStore.');
129       kvStore = store;
130       // Before performing related data operations, obtain a KV store instance.
131     });
132   } catch (e) {
133     let error = e as BusinessError;
134     console.error(`An unexpected error occurred. Code:${error.code},message:${error.message}`);
135   }
136   if (kvStore !== undefined) {
137     kvStore = kvStore as distributedKVStore.SingleKVStore;
138       // Perform subsequent operations.
139       //...
140   }
141   ```
142
1433. Use **put()** to add data to the KV store.<br>Example:
144
145   ```js
146   const KEY_TEST_STRING_ELEMENT = 'key_test_string';
147   const VALUE_TEST_STRING_ELEMENT = 'value_test_string';
148   try {
149     kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT, (err) => {
150       if (err !== undefined) {
151         console.error(`Failed to put data. Code:${err.code},message:${err.message}`);
152         return;
153       }
154       console.info('Succeeded in putting data.');
155     });
156   } catch (e) {
157     let error = e as BusinessError;
158     console.error(`An unexpected error occurred. Code:${error.code},message:${error.message}`);
159   }
160   ```
161
162   > **NOTE**
163   >
164   > The **put()** method adds a KV pair if the specified key does not exists and changes the value if the the specified key already exists.
165
1664. Use **get()** to obtain the value of a key.<br>Example:
167
168   ```js
169   const KEY_TEST_STRING_ELEMENT = 'key_test_string';
170   const VALUE_TEST_STRING_ELEMENT = 'value_test_string';
171   try {
172     kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT, (err) => {
173       if (err !== undefined) {
174         console.error(`Failed to put data. Code:${err.code},message:${err.message}`);
175         return;
176       }
177       console.info('Succeeded in putting data.');
178       kvStore = kvStore as distributedKVStore.SingleKVStore;
179       kvStore.get(KEY_TEST_STRING_ELEMENT, (err, data) => {
180         if (err != undefined) {
181           console.error(`Failed to get data. Code:${err.code},message:${err.message}`);
182           return;
183         }
184         console.info(`Succeeded in getting data. Data:${data}`);
185       });
186     });
187   } catch (e) {
188     let error = e as BusinessError;
189     console.error(`Failed to get data. Code:${error.code},message:${error.message}`);
190   }
191   ```
192
1935. Use **delete()** to delete the data of the specified key.<br>Example:
194
195   ```js
196   const KEY_TEST_STRING_ELEMENT = 'key_test_string';
197   const VALUE_TEST_STRING_ELEMENT = 'value_test_string';
198   try {
199     kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT, (err) => {
200       if (err !== undefined) {
201         console.error(`Failed to put data. Code:${err.code},message:${err.message}`);
202         return;
203       }
204       console.info('Succeeded in putting data.');
205       kvStore = kvStore as distributedKVStore.SingleKVStore;
206       kvStore.delete(KEY_TEST_STRING_ELEMENT, (err) => {
207         if (err !== undefined) {
208           console.error(`Failed to delete data. Code:${err.code},message:${err.message}`);
209           return;
210         }
211         console.info('Succeeded in deleting data.');
212       });
213     });
214   } catch (e) {
215     let error = e as BusinessError;
216     console.error(`An unexpected error occurred. Code:${error.code},message:${error.message}`);
217   }
218   ```
219