• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Creating a DataAbility
2
3
4To meet the basic requirements of the database storage service, implement the **Insert**, **Query**, **Update**, and **Delete** methods for a DataAbility. The **BatchInsert** and **ExecuteBatch** methods have already implemented the traversal logic, but not batch data processing.
5
6
7The following sample code shows how to create a DataAbility:
8
9```ts
10import featureAbility from '@ohos.ability.featureAbility'
11import dataAbility from '@ohos.data.dataAbility'
12import dataRdb from '@ohos.data.rdb'
13
14const TABLE_NAME = 'book'
15const STORE_CONFIG = { name: 'book.db' }
16const SQL_CREATE_TABLE = 'CREATE TABLE IF NOT EXISTS book(id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT NOT NULL, introduction TEXT NOT NULL)'
17let rdbStore: dataRdb.RdbStore = undefined
18
19export default {
20  onInitialized(abilityInfo) {
21    console.info('DataAbility onInitialized, abilityInfo:' + abilityInfo.bundleName)
22    let context = featureAbility.getContext()
23    dataRdb.getRdbStore(context, STORE_CONFIG, 1, (err, store) => {
24      console.info('DataAbility getRdbStore callback')
25      store.executeSql(SQL_CREATE_TABLE, [])
26      rdbStore = store
27    });
28  },
29  insert(uri, valueBucket, callback) {
30    console.info('DataAbility insert start')
31    rdbStore.insert(TABLE_NAME, valueBucket, callback)
32  },
33  batchInsert(uri, valueBuckets, callback) {
34    console.info('DataAbility batch insert start')
35    for (let i = 0;i < valueBuckets.length; i++) {
36      console.info('DataAbility batch insert i=' + i)
37      if (i < valueBuckets.length - 1) {
38        rdbStore.insert(TABLE_NAME, valueBuckets[i], (err: any, num: number) => {
39          console.info('DataAbility batch insert ret=' + num)
40        })
41      } else {
42        rdbStore.insert(TABLE_NAME, valueBuckets[i], callback)
43      }
44    }
45  },
46  query(uri, columns, predicates, callback) {
47    console.info('DataAbility query start')
48    let rdbPredicates = dataAbility.createRdbPredicates(TABLE_NAME, predicates)
49    rdbStore.query(rdbPredicates, columns, callback)
50  },
51  update(uri, valueBucket, predicates, callback) {
52    console.info('DataAbilityupdate start')
53    let rdbPredicates = dataAbility.createRdbPredicates(TABLE_NAME, predicates)
54    rdbStore.update(valueBucket, rdbPredicates, callback)
55  },
56  delete(uri, predicates, callback) {
57    console.info('DataAbilitydelete start')
58    let rdbPredicates = dataAbility.createRdbPredicates(TABLE_NAME, predicates)
59    rdbStore.delete(rdbPredicates, callback)
60  }
61};
62```
63