1# 创建DataAbility 2 3 4实现DataAbility中Insert、Query、Update、Delete接口的业务内容。保证能够满足数据库存储业务的基本需求。BatchInsert与ExecuteBatch接口已经在系统中实现遍历逻辑,依赖Insert、Query、Update、Delete接口逻辑,来实现数据的批量处理。 5 6 7创建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