On the basis of the SQLite database, the RDB allows you to operate data with or without native SQL statements. In OpenHarmony, an RDB is also called RDB store.
## 接口说明
## Available APIs
### 数据库的创建和删除
### Creating and Deleting an RDB Store
关系型数据库提供了数据库创建方式,以及对应的删除接口,涉及的API如下所示。
The following table describes APIs available for creating and deleting an RDB store.
表1 数据库创建和删除API
Table 1 APIs for creating and deleting an RDB store
| RdbStoreConfig | RdbStoreConfig(const std::string &path, <br> StorageMode storageMode = StorageMode::MODE_DISK, <br> bool readOnly = false, <br> const std::vector<uint8_t> &encryptKey = std::vector<uint8_t>(), <br> const std::string &journalMode = "", <br> const std::string &syncMode = "", <br> const std::string &databaseFileType = "", <br> const std::string &databaseFileSecurityLevel = "") | Configures an RDB store, including setting the name, storage mode, log mode, synchronization mode, and read-only mode, and encrypting the database. <ul><li>**path**: path of the database. </li><li>**readOnly**: whether the database is read-only. </li><li>**storageMode**: storage mode. </li><li>**encryptKey**: key used for database encryption. </li><li>**journalMode**: database logging mode. </li><li>**syncMode**: data synchronization mode. </li><li>**databaseFileType**: database type. </li><li>**databaseFileSecurityLevel**: security level. </li></ul>|
| RdbOpenCallback | int OnCreate(RdbStore &rdbStore) | 数据库创建时被回调,开发者可以在该方法中初始化表结构,并添加一些应用使用到的初始化数据。 |
| RdbOpenCallback | int OnCreate(RdbStore &rdbStore) | Called when an RDB store is created. You can add the method for initializing the table structure and add initialization data used by your application in the callback.|
| RdbOpenCallback | int OnUpgrade(RdbStore &rdbStore, int currentVersion, int targetVersion) | 数据库升级时被回调。 |
| RdbOpenCallback | int OnUpgrade(RdbStore &rdbStore, int currentVersion, int targetVersion) | Called when the RDB store is upgraded.|
| RdbOpenCallback | int OnDowngrade(RdbStore &rdbStore, int currentVersion, int targetVersion) | 数据库降级时被回调。 |
| RdbOpenCallback | int OnDowngrade(RdbStore &rdbStore, int currentVersion, int targetVersion) | Called when the RDB store is downgraded.|
| RdbHelper | std::shared_ptr\<RdbStore\> GetRdbStore(const RdbStoreConfig &config, int version, RdbOpenCallback &openCallback, int &errCode) | 根据配置创建或打开数据库。 |
| RdbHelper | std::shared_ptr\<RdbStore\> GetRdbStore(const RdbStoreConfig &config, int version, RdbOpenCallback &openCallback, int &errCode) | Creates or obtains an RDB store.|
| RdbHelper | int DeleteRdbStore(const std::string &path) | 删除指定的数据库。 |
| RdbHelper | int DeleteRdbStore(const std::string &path) | Deletes the specified RDB store.|
The RDB provides the database encryption capability. When creating an RDB store , you can add a key for security purposes. After that, the RDB store can be accessed only with the correct key.
表2 数据库修改密钥API
Table 2 API for changing the key
| 类名 | 接口名 | 描述 |
| Class| API| Description|
| ---- | ---- | ---- |
| ---- | ---- | ---- |
| RdbStore | int ChangeEncryptKey(const std::vector<uint8_t> &newKey) | 为数据库设置新的加密密钥。注:仅支持加密数据库更换加密密钥。 |
| RdbStore | int ChangeEncryptKey(const std::vector<uint8_t> &newKey) | Changes the encryption key for an RDB store. <br>Note: The encryption key can be changed only for an encrypted database.|
-**RdbPredicates**: With this class, you do not need to write complex SQL statements. Instead, you can combine SQL statements simply by calling methods in this class, such as **equalTo**, **notEqualTo**, **groupBy**, **orderByAsc**, and **beginsWith**.
| RdbPredicates | AbsPredicates *EqualTo(std::string field, std::string value) | Sets the **AbsPredicates** to match the field that is equal to the specified value.|
| RdbPredicates | AbsPredicates *NotEqualTo(std::string field, std::string value) | Sets the **AbsPredicates** to match the field that is not equal to the specified value.|
| RdbPredicates | AbsPredicates *BeginsWith(std::string field, std::string value) | Sets the **AbsPredicates** to match the field that starts with the specified value.|
| RdbPredicates | AbsPredicates *Between(std::string field, std::string low, std::string high) | Sets the **AbsPredicates** to match the field that is within the range specified by **low** and **high**.|
| RdbPredicates | AbsPredicates *OrderByAsc(std::string field) | Sets the **AbsPredicates** to match the column with values sorted in ascending order.|
| RdbPredicates | void SetWhereArgs(std::vector\<std::string\> whereArgs) | Sets **whereArgs**, which indicates the value of the placeholder in **whereClause**.|
### 数据表的增删改查
### Managing Data in an RDB Store
关系型数据库提供对本地数据增删改查操作的能力,相关API如下所示。
The RDB provides APIs for inserting, deleting, updating, and querying data in the local RDB store.
The RDB provides an API for inserting data through **ValuesBucket** in a data table. If the data is added, the row number of the data inserted is returned; otherwise, **-1** is returned.
| RdbStore | int Insert(int64_t &outRowId, const std::string &table, const ValuesBucket &initialValues) | Inserts data based on the passed table name and data in **ValuesBucket**. <ul><li>**table**: specifies the name of the target table. </li><li>**initialValues**: specifies the data, stored in **ValuesBucket**, to insert. A series of **put()** methods, such as **PutString(const std::string &columnName, const std::string &value)** and **PutDouble(const std::string &columnName, double value)**, are provided to add data to **ValuesBucket**.</li></ul> |
Call the **delete()** method to delete data meeting the conditions specified by **AbsRdbPredicates**. If the data is deleted, the row number of the deleted data is returned; otherwise, **0** is returned.
| RdbStore | int Delete(int &deletedRows, const AbsRdbPredicates &predicates) | Deletes data. <ul><li>**deletedRows**: specifies the number of rows to delete. </li><li>**predicates**: specifies the table name and conditions for deleting the data. **AbsRdbPredicates** has the following classes: <ul><li>**RdbPredicates**: specifies update conditions by calling its methods, such as **equalTo**. </li><li>**RawRdbPredicates**: specifies the table name, **whereClause** and **whereArgs** only.</li></ul></li></ul> |
Call the **update()** method to modify data based on the passed data and the conditions specified by **AbsRdbPredicates**. If the data is updated, the row number of the updated data is returned; otherwise, **0** is returned.
| RdbStore | int Update(int &changedRows, const ValuesBucket &values, const AbsRdbPredicates &predicates) | Updates the data that meets the conditions specified by predicates. <ul><li>**changedRows**: specifies the number of rows to update. </li><li>**values**: specifies the new data stored in **ValuesBucket**. </li><li>**predicates**: specifies the table name and conditions for the update operation. **AbsRdbPredicates** has the following classes: <ul><li>**RdbPredicates**: specifies update conditions by calling its methods, such as **equalTo**. </li><li>**RawRdbPredicates**: specifies the table name, **whereClause** and **whereArgs** only.</li></ul></li></ul> |
-查询
-Querying data
关系型数据库提供了两种查询数据的方式:
You can query data in an RDB store in either of the following ways:
| RdbStore | std::unique_ptr<AbsSharedResultSet> Query(const AbsRdbPredicates &predicates, const std::vector\<std::string\> columns) | Queries data. <ul><li>**predicates**: specifies the query conditions. **AbsRdbPredicates** has the following classes: <ul><li>**RdbPredicates**: specifies the query conditions by calling its methods, such as **equalTo**. </li><li>**RawRdbPredicates**: specifies the table name, **whereClause**, and **whereArgs** only. </li></ul><li>**columns**: specifies the number of columns returned.</li></ul></li></ul> |
| RdbStore | std::unique_ptr<AbsSharedResultSet> QuerySql(const std::string &sql, const std::vector\<std::string\> &selectionArgs = std::vector\<std::string\>()) | Executes the native SQL statements to query data. <ul><li>**sql**: specifies the native SQL statement. </li><li>**selectionArgs**: specifies the parameter values corresponding to the placeholders in the SQL statements. Set it to **null** if the **select** statement has no placeholder.</li></ul> |
A result set can be regarded as rows of data in the queried results. It allows you to traverse and access the data you have queried. The following table describes the external APIs of **ResultSet**.
表8 结果集API
Table 8 APIs for using the result set
| 类名 | 接口名 | 描述 |
| Class| API| Description|
| ---- | ---- | ---- |
| ---- | ---- | ---- |
| ResultSet | int GoTo(int offset) | 从结果集当前位置移动指定偏移量。 |
| ResultSet | int GoTo(int offset) | Moves the result set forwards or backwards by the specified offset relative to its current position.|
| ResultSet | int GoToRow(int position) | 将结果集移动到指定位置。 |
| ResultSet | int GoToRow(int position) | Moves the result set to the specified row.|
| ResultSet | int GoToNextRow() | 将结果集向后移动一行。 |
| ResultSet | int GoToNextRow() | Moves the result set to the next row.|
| ResultSet | int GoToPreviousRow() | 将结果集向前移动一行。 |
| ResultSet | int GoToPreviousRow() | Moves the result set to the previous row.|
| ResultSet | int IsStarted(bool &result) | 判断结果集是否被移动过。 |
| ResultSet | int IsStarted(bool &result) | Checks whether the result set has been moved.|
| ResultSet | int IsEnded(bool &result) | 判断结果集是否被移动到最后一行之后。 |
| ResultSet | int IsEnded(bool &result) | Checks whether the result set is moved after the last line.|
| ResultSet | int IsAtFirstRow(bool &result) | 判断结果集当前位置是否在第一行。 |
| ResultSet | int IsAtFirstRow(bool &result) | Checks whether the result set is located in the first row.|
| ResultSet | int IsAtLastRow(bool &result) | 判断结果集当前位置是否在最后一行。 |
| ResultSet | int IsAtLastRow(bool &result) | Checks whether the result set is located in the last row.|
| ResultSet | int GetRowCount(int &count) | 获取当前结果集中的记录条数。 |
| ResultSet | int GetRowCount(int &count) | Obtains the number of rows in the result set.|
| ResultSet | int GetColumnCount(int &count) | 获取结果集中的列数。 |
| ResultSet | int GetColumnCount(int &count) | Obtains the number of columns in the result set.|
| ResultSet | int GetBlob(int columnIndex, std::vector\<uint8_t\> &blob) | Obtains the values in the specified column of the current row, in a byte array.|
const CREATE_TABLE_TEST = "CREATE TABLE IF NOT EXISTS test (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, age INTEGER, salary REAL, blobType BLOB)";
const CREATE_TABLE_TEST = "CREATE TABLE IF NOT EXISTS test (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, age INTEGER, salary REAL, blobType BLOB)";
...
@@ -149,15 +149,13 @@
...
@@ -149,15 +149,13 @@
std::shared_ptr<RdbStore> store = RdbHelper::GetRdbStore(config, 1, callback, 0);
std::shared_ptr<RdbStore> store = RdbHelper::GetRdbStore(config, 1, callback, 0);
```
```
2.插入数据。
2.Insert data.
a. 构造要插入的数据,以ValuesBucket形式存储。
a. Create a **ValuesBucket** to store the data you need to insert.
b. 调用关系型数据库提供的插入接口。
b. Call the **insert()** method to insert data into the RDB store.
c. 创建数据库。
The sample code is as follows:
示例代码如下:
```
```
ValuesBucket values;
ValuesBucket values;
...
@@ -169,17 +167,17 @@
...
@@ -169,17 +167,17 @@
store->Insert(id, "test", values);
store->Insert(id, "test", values);
```
```
3.查询数据。
3.Query data.
a. 构造用于查询的谓词对象,设置查询条件。
a. Create a predicate that specifies query conditions.
b. 指定查询返回的数据列。
b. Specify the data columns to return in the result set.
c. 调用查询接口查询数据。
c. Call the **query()** method to query data.
d. 调用结果集接口,遍历返回结果。
d. Call the **ResultSet** APIs to traverse data in the result set.