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