• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Persisting RDB Store Data
2
3
4## When to Use
5
6A relational database (RDB) store is used to store data in complex relational models, such as the student information including names, student IDs, and scores of each subject, or employee information including names, employee IDs, and positions, based on SQLite. The data is more complex than key-value (KV) pairs due to strict mappings. You can use **RelationalStore** to implement persistence of this type of data.
7
8
9## Basic Concepts
10
11- **Predicates**: A representation of the property or feature of a data entity, or the relationship between data entities. It is used to define operation conditions.
12
13- **ResultSet**: a set of query results, which allows access to the required data in flexible modes.
14
15
16## Working Principles
17
18**RelationalStore** provides APIs for applications to perform data operations. With SQLite as the underlying persistent storage engine, **RelationalStore** provides SQLite database features, including transactions, indexes, views, triggers, foreign keys, parameterized queries, prepared SQL statements, and more.
19
20**Figure 1** Working mechanism
21
22![relationStore_local](figures/relationStore_local.jpg)
23
24
25## Constraints
26
27- The default logging mode is Write Ahead Log (WAL), and the default flushing mode is **FULL** mode.
28
29- An RDB store can be connected to a maximum of four connection pools for user read operations.
30
31- To ensure data accuracy, only one write operation is allowed at a time.
32
33- Once an application is uninstalled, related database files and temporary files on the device are automatically deleted.
34
35
36## Available APIs
37
38The following table lists the APIs used for RDB 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 [RDB Store](../reference/apis/js-apis-data-relationalStore.md).
39
40| API| Description|
41| -------- | -------- |
42| getRdbStore(context: Context, config: StoreConfig, callback: AsyncCallback<RdbStore>): void | Obtains a **RdbStore** instance to implement RDB store operations. You can set **RdbStore** parameters based on actual requirements and use **RdbStore** APIs to perform data operations.|
43| executeSql(sql: string, bindArgs: Array<ValueType>, callback: AsyncCallback<void>):void | Executes an SQL statement that contains specified arguments but returns no value.|
44| insert(table: string, values: ValuesBucket, callback: AsyncCallback<number>):void | Inserts a row of data into a table.|
45| update(values: ValuesBucket, predicates: RdbPredicates, callback: AsyncCallback<number>):void | Updates data in the RDB store based on the specified **RdbPredicates** instance.|
46| delete(predicates: RdbPredicates, callback: AsyncCallback<number>):void | Deletes data from the RDB store based on the specified **RdbPredicates** instance.|
47| query(predicates: RdbPredicates, columns: Array<string>, callback: AsyncCallback<ResultSet>):void | Queries data in the RDB store based on specified conditions.|
48| deleteRdbStore(context: Context, name: string, callback: AsyncCallback<void>): void | Deletes an RDB store.|
49
50
51## How to Develop
52
531. Obtain an **RdbStore** instance.<br> Example:
54
55   Stage model:
56
57   ```js
58   import relationalStore from '@ohos.data.relationalStore'; // Import the module.
59   import UIAbility from '@ohos.app.ability.UIAbility';
60
61   class EntryAbility extends UIAbility {
62     onWindowStageCreate(windowStage) {
63       const STORE_CONFIG = {
64         name: 'RdbTest.db', // Database file name.
65         securityLevel: relationalStore.SecurityLevel.S1 // Database security level.
66       };
67
68       const SQL_CREATE_TABLE ='CREATE TABLE IF NOT EXISTS EMPLOYEE (ID INTEGER PRIMARY KEY AUTOINCREMENT, NAME TEXT NOT NULL, AGE INTEGER, SALARY REAL, CODES BLOB)'; // SQL statement for creating a data table.
69
70       relationalStore.getRdbStore(this.context, STORE_CONFIG, (err, store) => {
71         if (err) {
72           console.error(`Failed to get RdbStore. Code:${err.code}, message:${err.message}`);
73           return;
74         }
75         console.info(`Succeeded in getting RdbStore.`);
76         store.executeSql(SQL_CREATE_TABLE); // Create a data table.
77
78         // Perform operations such as adding, deleting, modifying, and querying data in the RDB store.
79
80       });
81     }
82   }
83   ```
84
85   FA model:
86
87
88   ```js
89   import relationalStore from '@ohos.data.relationalStore'; // Import the module.
90   import featureAbility from '@ohos.ability.featureAbility';
91
92   // Obtain the context.
93   let context = featureAbility.getContext();
94
95   const STORE_CONFIG = {
96     name: 'RdbTest.db', // Database file name.
97     securityLevel: relationalStore.SecurityLevel.S1 // Database security level.
98   };
99
100   const SQL_CREATE_TABLE ='CREATE TABLE IF NOT EXISTS EMPLOYEE (ID INTEGER PRIMARY KEY AUTOINCREMENT, NAME TEXT NOT NULL, AGE INTEGER, SALARY REAL, CODES BLOB)'; // SQL statement for creating a data table.
101
102   relationalStore.getRdbStore(context, STORE_CONFIG, (err, store) => {
103     if (err) {
104       console.error(`Failed to get RdbStore. Code:${err.code}, message:${err.message}`);
105       return;
106     }
107     console.info(`Succeeded in getting RdbStore.`);
108     store.executeSql(SQL_CREATE_TABLE); // Create a data table.
109
110     // Perform operations such as adding, deleting, modifying, and querying data in the RDB store.
111
112   });
113   ```
114
115   > **NOTE**
116   >
117   > - The RDB store created by an application varies with the context. Multiple RDB stores are created for the same database name with different application contexts. For example, each UIAbility has its own context.
118   >
119   > - When an application calls **getRdbStore()** to obtain an RDB store instance for the first time, the corresponding database file is generated in the application sandbox. If you want to move the files of an RDB store to another place for view, you must also move the temporary files with finename extensions **-wal** or **-shm** in the same directory. Once an application is uninstalled, the database files and temporary files generated by the application on the device are also removed.
120
1212. Use **insert()** to insert data to the RDB store.
122
123   Example:
124
125   ```js
126   const valueBucket = {
127     'NAME': 'Lisa',
128     'AGE': 18,
129     'SALARY': 100.5,
130     'CODES': new Uint8Array([1, 2, 3, 4, 5])
131   };
132   store.insert('EMPLOYEE', valueBucket, (err, rowId) => {
133     if (err) {
134       console.error(`Failed to insert data. Code:${err.code}, message:${err.message}`);
135       return;
136     }
137     console.info(`Succeeded in inserting data. rowId:${rowId}`);
138})
139   ```
140
141   > **NOTE**
142>
143   > **RelationalStore** does not provide explicit flush operations for data persistence. Data inserted by **insert()** is stored in files persistently.
144
1453. Modify or delete data based on the specified **Predicates** instance.
146
147   Use **update()** to modify data and **delete()** to delete data.
148
149   Example:
150
151   ```js
152   // Modify data.
153   const valueBucket = {
154     'NAME': 'Rose',
155     'AGE': 22,
156     'SALARY': 200.5,
157     'CODES': new Uint8Array([1, 2, 3, 4, 5])
158   };
159   let predicates = new relationalStore.RdbPredicates('EMPLOYEE'); // Create predicates for the table named EMPLOYEE.
160   predicates.equalTo('NAME', 'Lisa'); // Modify the data of Lisa in the EMPLOYEE table to the specified data.
161   store.update(valueBucket, predicates, (err, rows) => {
162     if (err) {
163       console.error(`Failed to update data. Code:${err.code}, message:${err.message}`);
164       return;
165     }
166     console.info(`Succeeded in updating data. row count: ${rows}`);
167   })
168
169   // Delete data.
170   let predicates = new relationalStore.RdbPredicates('EMPLOYEE');
171   predicates.equalTo('NAME', 'Lisa');
172   store.delete(predicates, (err, rows) => {
173     if (err) {
174       console.error(`Failed to delete data. Code:${err.code}, message:${err.message}`);
175       return;
176     }
177     console.info(`Delete rows: ${rows}`);
178   })
179   ```
180
1814. Query data based on the conditions specified by **Predicates**.
182
183   Use **query()** to query data. The data obtained is returned in a **ResultSet** object.
184
185   Example:
186
187   ```js
188   let predicates = new relationalStore.RdbPredicates('EMPLOYEE');
189   predicates.equalTo('NAME', 'Rose');
190   store.query(predicates, ['ID', 'NAME', 'AGE', 'SALARY', 'CODES'], (err, resultSet) => {
191     if (err) {
192       console.error(`Failed to query data. Code:${err.code}, message:${err.message}`);
193       return;
194     }
195     console.info(`ResultSet column names: ${resultSet.columnNames}`);
196     console.info(`ResultSet column count: ${resultSet.columnCount}`);
197   })
198   ```
199
200   > **NOTE**
201   >
202   > Use **close()** to close the **ResultSet** that is no longer used in a timely manner so that the memory allocated can be released.
203
2045. Delete the RDB store.
205
206   Use **deleteRdbStore()** to delete the RDB store and related database files.
207
208   Example:
209
210   Stage model:
211
212
213   ```js
214   import UIAbility from '@ohos.app.ability.UIAbility';
215
216   class EntryAbility extends UIAbility {
217     onWindowStageCreate(windowStage) {
218       relationalStore.deleteRdbStore(this.context, 'RdbTest.db', (err) => {
219         if (err) {
220           console.error(`Failed to delete RdbStore. Code:${err.code}, message:${err.message}`);
221           return;
222         }
223         console.info('Succeeded in deleting RdbStore.');
224       });
225     }
226   }
227   ```
228
229   FA model:
230
231
232   ```js
233   import featureAbility from '@ohos.ability.featureAbility';
234
235   // Obtain the context.
236   let context = featureAbility.getContext();
237
238   relationalStore.deleteRdbStore(context, 'RdbTest.db', (err) => {
239     if (err) {
240       console.error(`Failed to delete RdbStore. Code:${err.code}, message:${err.message}`);
241       return;
242     }
243     console.info('Succeeded in deleting RdbStore.');
244   });
245   ```
246