• 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/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.
36
37   Example:
38   Stage model:
39
40
41   ```js
42   // Import the module.
43   import distributedKVStore from '@ohos.data.distributedKVStore';
44
45   // Stage model
46   import UIAbility from '@ohos.app.ability.UIAbility';
47
48   let kvManager;
49
50   export default class EntryAbility extends UIAbility {
51     onCreate() {
52       let context = this.context;
53       const kvManagerConfig = {
54         context: context,
55         bundleName: 'com.example.datamanagertest'
56       };
57       try {
58         // Create a KVManager instance.
59         kvManager = distributedKVStore.createKVManager(kvManagerConfig);
60         console.info('Succeeded in creating KVManager.');
61         // Create and obtain the database.
62       } catch (e) {
63         console.error(`Failed to create KVManager. Code:${e.code},message:${e.message}`);
64       }
65     }
66   }
67   ```
68
69   FA model:
70
71
72   ```js
73   // Import the module.
74   import distributedKVStore from '@ohos.data.distributedKVStore';
75
76   // FA model
77   import featureAbility from '@ohos.ability.featureAbility';
78
79   let kvManager;
80   let context = featureAbility.getContext(); // Obtain the context.
81   const kvManagerConfig = {
82     context: context,
83     bundleName: 'com.example.datamanagertest'
84   };
85   try {
86     kvManager = distributedKVStore.createKVManager(kvManagerConfig);
87     console.info('Succeeded in creating KVManager.');
88     // Create and obtain the database.
89   } catch (e) {
90     console.error(`Failed to create KVManager. Code:${e.code},message:${e.message}`);
91   }
92   ```
93
942. Create and obtain a KV store.
95
96   Example:
97   ```js
98   try {
99     const options = {
100       createIfMissing: true, // Whether to create a KV store when the database file does not exist. By default, a KV store is created.
101       encrypt: false, // Whether to encrypt the KV store. By default, KV stores are not encrypted.
102       backup: false, // Whether to back up database files. By default, the database files are backed up.
103       autoSync: true, // Whether to automatically synchronize database files. The value **true** means to automatically synchronize database files; the value **false** (default) means the opposite.
104       kvStoreType: distributedKVStore.KVStoreType.SINGLE_VERSION, // Type of the KV store to create. By default, a device KV store is created.
105       securityLevel: distributedKVStore.SecurityLevel.S2 // Security level of the KV store.
106     };
107     // storeId uniquely identifies a KV store.
108     kvManager.getKVStore('storeId', options, (err, kvStore) => {
109       if (err) {
110         console.error(`Failed to get KVStore. Code:${err.code},message:${err.message}`);
111         return;
112       }
113       console.info('Succeeded in getting KVStore.');
114       // Perform related data operations.
115     });
116   } catch (e) {
117     console.error(`An unexpected error occurred. Code:${e.code},message:${e.message}`);
118   }
119   ```
120
1213. Use **put()** to add data to the KV store.
122
123   Example:
124   ```js
125   const KEY_TEST_STRING_ELEMENT = 'key_test_string';
126   const VALUE_TEST_STRING_ELEMENT = 'value_test_string';
127   try {
128     kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT, (err) => {
129       if (err !== undefined) {
130         console.error(`Failed to put data. Code:${err.code},message:${err.message}`);
131         return;
132       }
133       console.info('Succeeded in putting data.');
134     });
135   } catch (e) {
136     console.error(`An unexpected error occurred. Code:${e.code},message:${e.message}`);
137   }
138   ```
139
140   > **NOTE**
141   >
142   > 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.
143
1444. Use **get()** to obtain the value of a key.
145
146   Example:
147   ```js
148   const KEY_TEST_STRING_ELEMENT = 'key_test_string';
149   const VALUE_TEST_STRING_ELEMENT = 'value_test_string';
150   try {
151     kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT, (err) => {
152       if (err !== undefined) {
153         console.error(`Failed to put data. Code:${err.code},message:${err.message}`);
154         return;
155       }
156       console.info('Succeeded in putting data.');
157       kvStore.get(KEY_TEST_STRING_ELEMENT, (err, data) => {
158         if (err !== undefined) {
159           console.error(`Failed to get data. Code:${err.code},message:${err.message}`);
160           return;
161         }
162         console.info(`Succeeded in getting data. data:${data}`);
163       });
164     });
165   } catch (e) {
166     console.error(`Failed to get data. Code:${e.code},message:${e.message}`);
167   }
168   ```
169
1705. Use **delete()** to delete the data of the specified key.
171
172   Example:
173   ```js
174   const KEY_TEST_STRING_ELEMENT = 'key_test_string';
175   const VALUE_TEST_STRING_ELEMENT = 'value_test_string';
176   try {
177     kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT, (err) => {
178       if (err !== undefined) {
179         console.error(`Failed to put data. Code:${err.code},message:${err.message}`);
180         return;
181       }
182       console.info('Succeeded in putting data.');
183       kvStore.delete(KEY_TEST_STRING_ELEMENT, (err) => {
184         if (err !== undefined) {
185           console.error(`Failed to delete data. Code:${err.code},message:${err.message}`);
186           return;
187         }
188         console.info('Succeeded in deleting data.');
189       });
190     });
191   } catch (e) {
192     console.error(`An unexpected error occurred. Code:${e.code},message:${e.message}`);
193   }
194   ```
195