database-preference-guidelines.md 7.4 KB
Newer Older
A
annie_wangli 已提交
1
# Lightweight Data Store Development
Z
zengyawen 已提交
2

A
annie_wangli 已提交
3
## When to Use
Z
zengyawen 已提交
4

A
annie_wangli 已提交
5
The lightweight data store is ideal for storing lightweight and frequently used data, but not for storing a large amount of data or data with frequent changes. The application data is persistently stored on a device in the form of files. Note that the instance accessed by an application contains all data of the file. The data is always loaded to the memory of the device until the application removes it from the memory. The application can perform data operations using the **Storage** APIs.
Z
zengyawen 已提交
6

A
annie_wangli 已提交
7
## Available APIs
Z
zengyawen 已提交
8

A
annie_wangli 已提交
9
The lightweight data store provides applications with data processing capability and allows applications to perform lightweight data storage and query. Data is stored in key-value (KV) pairs. Keys are of the string type, and values can be of the number, string, or Boolean type.
Z
zengyawen 已提交
10 11 12

**Creating a Storage Instance**

A
annie_wangli 已提交
13 14 15 16 17 18 19
Create a **Storage** instance for data operations. A **Storage** instance is created after data is read from a specified file and loaded to the instance.

**Table 1** API for creating a **Storage** instance

| Package             | API                                     | Description                                       |
| ----------------- | ------------------------------------------- | ------------------------------------------- |
| ohos.data.storage | getStorage(path: string): Promise\<Storage> | Obtains the **Storage** singleton corresponding to a file for data operations.|
Z
zengyawen 已提交
20 21 22

**Writing Data**

A
annie_wangli 已提交
23 24 25 26 27 28 29
Call the **put()** method to add or modify data in a **Storage** instance.

**Table 2** API for writing data

| Class   | API                                            | Description                                           |
| ------- | -------------------------------------------------- | ----------------------------------------------- |
| Storage | put(key: string, value: ValueType): Promise\<void> | Writes data of the number, string, and Boolean types.|
Z
zengyawen 已提交
30 31 32

**Reading Data**

A
annie_wangli 已提交
33 34 35 36 37 38 39
Call the **get()** method to read data from a **Storage** instance.

**Table 3** API for reading data

| Class   | API                                                    | Description                                           |
| ------- | ---------------------------------------------------------- | ----------------------------------------------- |
| Storage | get(key: string, defValue: ValueType): Promise\<ValueType> | Reads data of the number, string, and Boolean types.|
Z
zengyawen 已提交
40 41 42

**Storing Data Persistently**

A
annie_wangli 已提交
43
Call the **flush()** method to write the cached data back to its text file for persistent storage.
Z
zengyawen 已提交
44

A
annie_wangli 已提交
45
**Table 4** API for data persistence
Z
zengyawen 已提交
46

A
annie_wangli 已提交
47 48 49
| Class   | API                 | Description                                   |
| ------- | ----------------------- | --------------------------------------- |
| Storage | flush(): Promise\<void> | Writes data in the **Storage** instance back to its file through an asynchronous thread.|
Z
zengyawen 已提交
50

A
annie_wangli 已提交
51
**Observing Data Changes**
Z
zengyawen 已提交
52

A
annie_wangli 已提交
53
Specify **StorageObserver** as the callback to subscribe to data changes. When the value of the subscribed key is changed and the **flush()** method is executed, **StorageObserver** will be invoked.
Z
zengyawen 已提交
54

A
annie_wangli 已提交
55
**Table 5** APIs for observing data changes
Z
zengyawen 已提交
56

A
annie_wangli 已提交
57 58 59 60 61 62
| Class   | API                                                      | Description          |
| ------- | ------------------------------------------------------------ | -------------- |
| Storage | on(type: 'change', callback: Callback\<StorageObserver>): void | Subscribe to data changes.|
| Storage | off(type: 'change', callback: Callback\<StorageObserver>): void | Unsubscribes from data changes. |

**Deleting Data**
Z
zengyawen 已提交
63

A
annie_wangli 已提交
64 65 66 67 68 69 70 71 72 73 74 75 76
Use the following APIs to delete a **Storage** instance or data file.

**Table 6** APIs for deleting data

| Package             | API                                              | Description                                                        |
| ----------------- | ---------------------------------------------------- | ------------------------------------------------------------ |
| ohos.data.storage | deleteStorage(path: string): Promise\<void>          | Deletes a **Storage** instance from the cache and deletes its file from the device.|
| ohos.data.storage | removeStorageFromCache(path: string): Promise\<void> | Deletes a **Storage** instance from the cache to release memory.       |

## How to Develop

1. Import @ohos.data.storage and related modules to the development environment.

77
   ```js
A
annie_wangli 已提交
78 79 80 81 82 83 84
   import dataStorage from '@ohos.data.storage'
   import featureAbility from '@ohos.ability.featureAbility'  // Used to obtain the file storage path.
   ```

2. Create a **Storage** instance.

   Read the specified file and load its data to the **Storage** instance for data operations.
85
   ```js
A
annie_wangli 已提交
86 87 88 89 90 91 92 93 94 95 96 97
   var context = featureAbility.getContext()
   context.getFilesDir().then(() => {
    console.info("======================>getFilesDirPromsie====================>");
   });

   let promise = dataStorage.getStorage(path + '/mystore')
   ```

3. Write data.

   Use the **put()** method of the **Storage** class to write data to the cached **Storage** instance.

98
   ```js
A
annie_wangli 已提交
99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114
   promise.then((storage) => {
           let getPromise = storage.put('startup', 'auto') // Save data to the Storage instance.
       getPromise.then(() => {
           console.info("Put the value of startup successfully.")
       }).catch((err) => {
           console.info("Put the value of startup failed with err: " + err)
       })
   }).catch((err) => {
       console.info("Get the storage failed")
   })
   ```

4. Read data.

   Use the **get()** method of the **Storage** class to read data.

115
   ```js
A
annie_wangli 已提交
116 117 118 119 120 121 122 123 124 125 126 127 128 129 130
   promise.then((storage) => {
       let getPromise = storage.get('startup', 'default')
       getPromise.then((value) => {
           console.info("The value of startup is " + value)
       }).catch((err) => {
           console.info("Get the value of startup failed with err: " + err)
       })
   }).catch((err) => {
       console.info("Get the storage failed")})
   ```

5. Store data persistently.

   Use the **flush()** or **flushSync()** method to flush data in the **Storage** instance to its file.

131
   ```js
A
annie_wangli 已提交
132 133 134 135 136 137 138
   storage.flush();
   ```

6.  Observe data changes.

   Specify **StorageObserver** as the callback to subscribe to data changes for an application. When the value of the subscribed key is changed and the **flush()** method is executed, **StorageObserver** will be invoked. Unregister the **StorageObserver** when it is no longer required.

139
   ```js
A
annie_wangli 已提交
140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157
   promise.then((storage) => {
       var observer = function (key) {
           console.info("The key of " + key + " changed.")
       }
       storage.on('change', observer)
           storage.putSync('startup', 'auto') // Modify data in the Storage instance.
           storage.flushSync() // Trigger the StorageObserver callback.
   
           storage.off(...change..., observer) // Unsubscribe from the data changes.
   }).catch((err) => {
       console.info("Get the storage failed")
   })
   ```

7. Delete the specified file.

   Use the **deleteStorage** method to delete the **Storage** singleton of the specified file from the memory, and delete the specified file, its backup file, and damaged files. After the specified files are deleted, the application cannot use that instance to perform any data operation. Otherwise, data inconsistency will occur. The deleted data and files cannot be restored.

158
   ```js
A
annie_wangli 已提交
159 160 161 162 163 164
   let promise = dataStorage.deleteStorage(path + '/mystore')
   promise.then(() => {
       console.info("Deleted successfully.")
   }).catch((err) => {
       console.info("Deleted failed with err: " + err)})
   ```