Less persistent data storage, we can choose user preferences or distributed key-value database for operation, if the first two can not be met, in Hongmeng, also gives us a relational database for the operation of the data between the operation, and Android is similar to a relational database based on the SQLite component, provides a complete set of mechanisms for the management of local databases, but also External to provide a series of add, delete, change, check and other interfaces, very convenient, in order to more convenient operation of the data, the current system Api made a simple layer of encapsulation.
The content of this post is roughly as follows:
1. Remote address dependency
2, database creation and table creation
3. Database additions, deletions and changes
4. Summary of use
I. Remote address dependency
Set up the three-way package dependency in oh-package.json5 of the project module with the following configuration example:
"dependencies": { "@abner/datastore": "^1.0.0"}
II. Database creation and table creation
1. Database creation
The database is created, by default, during initialization, just initialize it in AbilityStage.
DbUtil.getInstance().init(this.context)
Attributes
Attributes | type | summarize |
---|---|---|
context | Context | context |
storeConfig | relationalStore.StoreConfig | Database related configurations can be left untransmitted by default, a default abner_data.db database will be created, securityLevel is S3, encrypt is true. |
storeConfig
Attributes | type | summarize |
---|---|---|
name | string | The database file name, which is also the database unique identifier. |
securityLevel | SecurityLevel | Set the database security level. |
encrypt | boolean | Specifies whether the database is encrypted or not, the default is not encrypted. true:Encrypted. false:Non-encrypted. |
dataGroupId | string | The application group ID, which needs to be obtained from the application marketplace. Model Constraints: This attribute is only available under the Stage model. Starting with API version 10, this optional parameter is supported. Specifies that the RdbStore instance is created under the sandbox path corresponding to this dataGroupId. When this parameter is not filled, the RdbStore instance is created under this application sandbox directory by default. |
customDir | string | Database customization path. Usage constraints: The database path size is limited to 128 bytes, if it exceeds this size, the library will fail and return an error. |
autoCleanDirtyData | boolean | Specify whether to automatically clean up the data synchronized locally after deletion in the cloud, true means automatically clean up, false means manually clean up, the default is automatically clean up. |
2、Data table creation
Data tables are created in two ways, either by sql statement execution or by object form execution.
sql statement execution
DbUtil.getInstance()
.executeSql("CREATE TABLE table_name(id INTEGER PRIMARY KEY AUTOINCREMENT,name VARCHAR(50),age INT)")
Object form implementation [recommended
object form, weakened the sql statement, but itself is still in the form of sql to create a data table, just the business layer of the operation, no sql operation, the implementation is very simple and intuitive, the first parameter is the name of the data table that is table_name, the second parameter is an object, that is, the fields of the data table, each field, you need to specify the data type and other necessary parameters, such as primary key, self incremental length, etc.. For example, the primary key, self-incrementing, length and so on.
DbUtil.getInstance().createTable("table_name", {
"id": { type: DbTableFieldType.INTEGER, isPrimaryKey: true, isAutoIncrement: true },
"name": { type: DbTableFieldType.VARCHAR, length: 120 },
"age": { type: DbTableFieldType.INT, length: 30 }
})
III. Database additions, deletions and changes
1、Add
General Storage
A ValuesBucket object needs to be defined for passing.
const valueBucket1: ValuesBucket = {
'name': "AbnerMing",
'age': 18,
}
DbUtil.getInstance().insert("table_name", valueBucket1)
object storage
let bean = new DbDataBean()
bean.name = "AbnerMing"
bean.age = 18
DbUtil.getInstance().insertBean("table_name", bean)
2、Delete
Ordinary deletion
You need to use RdbPredicates object to set the filter conditions, you can just check the official website Api.
let deleteRdbPredicates = new relationalStore.RdbPredicates("table_name");
deleteRdbPredicates.equalTo("id", 1);
DbUtil.getInstance().delete(deleteRdbPredicates)
Object Deletion
Similar to normal deletion, except that the RdbPredicates object is simply encapsulated, and you need to call the filterRdbPredicates method to set the filter conditions.
DbUtil.getInstance()
.filterRdbPredicates({ equalTo: { "id": 2 } })
.deleteBean("table_name")
3、Change
General Modifications
const valueBucket: ValuesBucket = {
'name': "ming",
'age': 28,
}
let upDataRdbPredicates = new relationalStore.RdbPredicates("table_name");
upDataRdbPredicates.equalTo("id", 1)
DbUtil.getInstance().update(upDataRdbPredicates, valueBucket)
Object Modification
The filterRdbPredicates method is the filter condition, i.e. which data you want to change.
let uBean = new DbDataBean()
uBean.name = "Ming"
uBean.age = 20
DbUtil.getInstance()
.filterRdbPredicates({ equalTo: { "id": 2 } })
.updateBean("table_name", uBean)
4、Find
general inquiry
let predicates = new relationalStore.RdbPredicates("table_name");
DbUtil.getInstance().query(predicates, (resultSet: relationalStore.ResultSet) => {
while (resultSet.goToNextRow()) {
const id = resultSet.getLong(resultSet.getColumnIndex("id"));
const name = resultSet.getString(resultSet.getColumnIndex("name"));
const age = resultSet.getLong(resultSet.getColumnIndex("age"));
}
})
object search
Get All
DbUtil.getInstance()
.queryAllBean<DbDataBean>("table_name", (data) => {
})
Get a single
DbUtil.getInstance()
.filterRdbPredicates({ equalTo: { "id": 1 } })
.queryBean<DbDataBean>("table_name", (data) => {
})
IV. Summary of use
Each method is reserved for a variety of invocation methods, such as the use of callback asynchronous callback or the use of Promise asynchronous callback , or synchronous execution , we can use the process , according to their own business needs for selective calls , but also exposed the success and failure of the method , you can target to determine the execution process in the implementation of the implementation of the success or not.
The following case:
DbUtil.getInstance().delete(deleteRdbPredicates,
(rows: number)=>{
},
(err: BusinessError)=>{
})