1# Interface (Transaction) 2<!--Kit: ArkData--> 3<!--Subsystem: DistributedDataManager--> 4<!--Owner: @baijidong--> 5<!--Designer: @widecode; @htt1997--> 6<!--Tester: @yippo; @logic42--> 7<!--Adviser: @ge-yafang--> 8 9> **说明:** 10> 11> - 本模块首批接口从API version 9开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 12> 13> - 本Interface首批接口从API version 14开始支持。 14 15提供以事务方式管理数据库的方法。事务对象是通过[createTransaction](arkts-apis-data-relationalStore-RdbStore.md#createtransaction14)接口创建的,不同事务对象之间的操作是隔离的,不同类型事务的区别见[TransactionType](arkts-apis-data-relationalStore-e.md#transactiontype14) 。 16 17当前关系型数据库同一时刻仅支持一个写事务,所以如果当前[RdbStore](arkts-apis-data-relationalStore-RdbStore.md)存在写事务未释放,创建IMMEDIATE或EXCLUSIVE事务会返回14800024错误码。如果是创建的DEFERRED事务,则可能在首次使用DEFERRED事务调用写操作时返回14800024错误码。通过IMMEDIATE或EXCLUSIVE创建写事务或者DEFERRED事务升级到写事务之后,[RdbStore](arkts-apis-data-relationalStore-RdbStore.md)的写操作也会返回14800024错误码。 18 19当事务并发量较高且写事务持续时间较长时,返回14800024错误码的次数可能会变多,开发者可以通过减少事务占用时长减少14800024出现的次数,也可以通过重试的方式处理14800024错误码。 20 21在使用以下API前,请先通过[createTransaction](./arkts-apis-data-relationalStore-RdbStore.md#createtransaction14)方法获取Transaction实例,再通过此实例调用对应方法。 22 23**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core 24 25**示例:** 26 27```ts 28import { UIAbility } from '@kit.AbilityKit'; 29import { BusinessError } from '@kit.BasicServicesKit'; 30import { window } from '@kit.ArkUI'; 31 32let store: relationalStore.RdbStore | undefined = undefined; 33 34export default class EntryAbility extends UIAbility { 35 async onWindowStageCreate(windowStage: window.WindowStage) { 36 const STORE_CONFIG: relationalStore.StoreConfig = { 37 name: 'RdbTest.db', 38 securityLevel: relationalStore.SecurityLevel.S3 39 }; 40 41 try { 42 const rdbStore = await relationalStore.getRdbStore(this.context, STORE_CONFIG); 43 store = rdbStore; 44 console.info('Get RdbStore successfully.'); 45 } catch (error) { 46 const err = error as BusinessError; 47 console.error(`Get RdbStore failed, code is ${err.code},message is ${err.message}`); 48 } 49 50 if (store != undefined) { 51 await store.executeSql('CREATE TABLE IF NOT EXISTS EMPLOYEE (ID INTEGER PRIMARY KEY AUTOINCREMENT, NAME TEXT NOT NULL, AGE INTEGER, SALARY REAL, CODES BLOB, IDENTITY UNLIMITED INT, ASSETDATA ASSET, ASSETSDATA ASSETS, FLOATARRAY floatvector(128))'); 52 store.createTransaction().then(async (transaction: relationalStore.Transaction) => { 53 console.info(`createTransaction success`); 54 // 成功获取到事务对象后执行后续操作 55 }).catch((err: BusinessError) => { 56 console.error(`createTransaction failed, code is ${err.code},message is ${err.message}`); 57 }); 58 } 59 } 60} 61``` 62 63## 导入模块 64 65```ts 66import { relationalStore } from '@kit.ArkData'; 67``` 68 69## commit<sup>14+</sup> 70 71commit(): Promise<void> 72 73提交已执行的SQL语句。如果是使用异步接口执行sql语句,请确保异步接口执行完成之后再调用commit接口,否则可能会丢失SQL操作。调用commit接口之后,该Transaction对象及创建的ResultSet对象都将被关闭。 74 75**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core 76 77**返回值**: 78 79| 类型 | 说明 | 80| ------------------- | ------------------------- | 81| Promise<void> | 无返回结果的Promise对象。 | 82 83**错误码:** 84 85以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)和[关系型数据库错误码](errorcode-data-rdb.md)。其中,14800011错误码处理可参考[数据库备份与恢复](../../database/data-backup-and-restore.md)。 86 87| **错误码ID** | **错误信息** | 88|-----------| ------------------------------------------------------------ | 89| 14800000 | Inner error. | 90| 14800011 | Failed to open the database because it is corrupted. | 91| 14800014 | The RdbStore or ResultSet is already closed. | 92| 14800023 | SQLite: Access permission denied. | 93| 14800024 | SQLite: The database file is locked. | 94| 14800026 | SQLite: The database is out of memory. | 95| 14800027 | SQLite: Attempt to write a readonly database. | 96| 14800028 | SQLite: Some kind of disk I/O error occurred. | 97| 14800029 | SQLite: The database is full. | 98 99**示例:** 100 101```ts 102if (store != undefined) { 103 try { 104 const transaction = await store.createTransaction(); 105 try { 106 await transaction.execute('CREATE TABLE IF NOT EXISTS test (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT NOT NULL, age INTEGER, salary REAL)'); 107 await transaction.commit(); 108 } catch (error) { 109 const err = error as BusinessError; 110 await transaction.rollback(); 111 console.error(`execute sql failed, code is ${err.code},message is ${err.message}`); 112 } 113 } catch (error) { 114 const err = error as BusinessError; 115 console.error(`createTransaction failed, code is ${err.code},message is ${err.message}`); 116 } 117} 118``` 119 120## rollback<sup>14+</sup> 121 122rollback(): Promise<void> 123 124回滚已经执行的SQL语句。调用rollback接口之后,该Transaction对象及创建的ResultSet对象都会被关闭。 125 126**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core 127 128**返回值**: 129 130| 类型 | 说明 | 131| ------------------- | ------------------------- | 132| Promise<void> | 无返回结果的Promise对象。 | 133 134**错误码:** 135 136以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)和[关系型数据库错误码](errorcode-data-rdb.md)。其中,14800011错误码处理可参考[数据库备份与恢复](../../database/data-backup-and-restore.md)。 137 138| **错误码ID** | **错误信息** | 139|-----------| ------------------------------------------------------------ | 140| 14800000 | Inner error. | 141| 14800011 | Failed to open the database because it is corrupted. | 142| 14800014 | The RdbStore or ResultSet is already closed. | 143| 14800023 | SQLite: Access permission denied. | 144| 14800024 | SQLite: The database file is locked. | 145| 14800026 | SQLite: The database is out of memory. | 146| 14800027 | SQLite: Attempt to write a readonly database. | 147| 14800028 | SQLite: Some kind of disk I/O error occurred. | 148| 14800029 | SQLite: The database is full. | 149 150**示例:** 151 152```ts 153if (store != undefined) { 154 try { 155 const transaction = await store.createTransaction(); 156 try { 157 await transaction.execute('DELETE FROM TEST WHERE age = ? OR age = ?', ['18', '20']); 158 await transaction.commit(); 159 } catch (error) { 160 const err = error as BusinessError; 161 await transaction.rollback(); 162 console.error(`execute sql failed, code is ${err.code},message is ${err.message}`); 163 } 164 } catch (error) { 165 const err = error as BusinessError; 166 console.error(`createTransaction failed, code is ${err.code},message is ${err.message}`); 167 } 168} 169``` 170 171## insert<sup>14+</sup> 172 173insert(table: string, values: ValuesBucket, conflict?: ConflictResolution): Promise<number> 174 175向目标表中插入一行数据,使用Promise异步回调。由于共享内存大小限制为2Mb,因此单条数据的大小需小于2Mb,否则会查询失败。 176 177**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core 178 179**参数:** 180 181| 参数名 | 类型 | 必填 | 说明 | 182| -------- | ------------------------------------------- | ---- | -------------------------- | 183| table | string | 是 | 指定的目标表名。 | 184| values | [ValuesBucket](arkts-apis-data-relationalStore-t.md#valuesbucket) | 是 | 表示要插入到表中的数据行。 | 185| conflict | [ConflictResolution](arkts-apis-data-relationalStore-e.md#conflictresolution10)| 否 | 指定冲突解决模式。默认值是relationalStore.ConflictResolution.ON_CONFLICT_NONE。 | 186 187**返回值**: 188 189| 类型 | 说明 | 190| --------------------- | ------------------------------------------------- | 191| Promise<number> | Promise对象。如果操作成功,返回行ID;否则返回-1。 | 192 193**错误码:** 194 195以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)和[关系型数据库错误码](errorcode-data-rdb.md)。其中,14800011错误码处理可参考[数据库备份与恢复](../../database/data-backup-and-restore.md)。 196 197| **错误码ID** | **错误信息** | 198|-----------| ------------------------------------------------------------ | 199| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. | 200| 14800000 | Inner error. | 201| 14800011 | Failed to open the database because it is corrupted. | 202| 14800014 | The RdbStore or ResultSet is already closed. | 203| 14800021 | SQLite: Generic error. Possible causes: Insert failed or the updated data does not exist. | 204| 14800023 | SQLite: Access permission denied. | 205| 14800024 | SQLite: The database file is locked. | 206| 14800025 | SQLite: A table in the database is locked. | 207| 14800026 | SQLite: The database is out of memory. | 208| 14800027 | SQLite: Attempt to write a readonly database. | 209| 14800028 | SQLite: Some kind of disk I/O error occurred. | 210| 14800029 | SQLite: The database is full. | 211| 14800031 | SQLite: TEXT or BLOB exceeds size limit. | 212| 14800033 | SQLite: Data type mismatch. | 213| 14800047 | The WAL file size exceeds the default limit. | 214 215**示例:** 216 217```ts 218const valueBucket1: relationalStore.ValuesBucket = { 219 NAME: 'Lisa', 220 AGE: 18, 221 SALARY: 100.5, 222 CODES: new Uint8Array([1, 2, 3, 4, 5]) 223}; 224 225if (store != undefined) { 226 try { 227 const transaction = await store.createTransaction(); 228 try { 229 const rowId = await transaction.insert('EMPLOYEE', valueBucket1, relationalStore.ConflictResolution.ON_CONFLICT_REPLACE); 230 await transaction.commit(); 231 console.info(`Insert is successful, rowId = ${rowId}`); 232 } catch (error) { 233 const err = error as BusinessError; 234 await transaction.rollback(); 235 console.error(`Insert is failed, code is ${err.code},message is ${err.message}`); 236 } 237 } catch (error) { 238 const err = error as BusinessError; 239 console.error(`createTransaction failed, code is ${err.code},message is ${err.message}`); 240 } 241} 242``` 243 244## insertSync<sup>14+</sup> 245 246insertSync(table: string, values: ValuesBucket | sendableRelationalStore.ValuesBucket, conflict?: ConflictResolution): number 247 248向目标表中插入一行数据。由于共享内存大小限制为2Mb,因此单条数据的大小需小于2Mb,否则会查询失败。 249 250**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core 251 252**参数:** 253 254| 参数名 | 类型 | 必填 | 说明 | 255| -------- | ------------------------------------------- | ---- | ------------------------------------------------------------ | 256| table | string | 是 | 指定的目标表名。 | 257| values | [ValuesBucket](arkts-apis-data-relationalStore-t.md#valuesbucket) \| [sendableRelationalStore.ValuesBucket](./js-apis-data-sendableRelationalStore.md#valuesbucket) | 是 | 表示要插入到表中的数据行。 | 258| conflict | [ConflictResolution](arkts-apis-data-relationalStore-e.md#conflictresolution10)| 否 | 指定冲突解决模式。默认值是relationalStore.ConflictResolution.ON_CONFLICT_NONE。 | 259 260**返回值**: 261 262| 类型 | 说明 | 263| ------ | ------------------------------------ | 264| number | 如果操作成功,返回行ID;否则返回-1。 | 265 266**错误码:** 267 268以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)和[关系型数据库错误码](errorcode-data-rdb.md)。其中,14800011错误码处理可参考[数据库备份与恢复](../../database/data-backup-and-restore.md)。 269 270| **错误码ID** | **错误信息** | 271| ------------ | ------------------------------------------------------------ | 272| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. | 273| 14800000 | Inner error. | 274| 14800011 | Failed to open the database because it is corrupted. | 275| 14800014 | The RdbStore or ResultSet is already closed. | 276| 14800021 | SQLite: Generic error. Possible causes: Insert failed or the updated data does not exist. | 277| 14800023 | SQLite: Access permission denied. | 278| 14800024 | SQLite: The database file is locked. | 279| 14800025 | SQLite: A table in the database is locked. | 280| 14800026 | SQLite: The database is out of memory. | 281| 14800027 | SQLite: Attempt to write a readonly database. | 282| 14800028 | SQLite: Some kind of disk I/O error occurred. | 283| 14800029 | SQLite: The database is full. | 284| 14800031 | SQLite: TEXT or BLOB exceeds size limit. | 285| 14800033 | SQLite: Data type mismatch. | 286| 14800047 | The WAL file size exceeds the default limit. | 287 288**示例:** 289 290```ts 291let value5 = 'Lisa'; 292let value6 = 18; 293let value7 = 100.5; 294let value8 = new Uint8Array([1, 2, 3, 4, 5]); 295 296const valueBucket2: relationalStore.ValuesBucket = { 297 NAME: value5, 298 AGE: value6, 299 SALARY: value7, 300 CODES: value8 301}; 302if (store != undefined) { 303 try { 304 const transaction = await store.createTransaction(); 305 try { 306 let rowId: number = transaction.insertSync( 307 'EMPLOYEE', 308 valueBucket2, 309 relationalStore.ConflictResolution.ON_CONFLICT_REPLACE 310 ); 311 await transaction.commit(); 312 console.info(`Insert is successful, rowId = ${rowId}`); 313 } catch (e) { 314 await transaction.rollback(); 315 console.error(`Insert is failed, code is ${e.code},message is ${e.message}`); 316 } 317 } catch (error) { 318 const err = error as BusinessError; 319 console.error(`createTransaction failed, code is ${err.code},message is ${err.message}`); 320 } 321} 322``` 323 324## batchInsert<sup>14+</sup> 325 326batchInsert(table: string, values: Array<ValuesBucket>): Promise<number> 327 328向目标表中插入一组数据,使用Promise异步回调。 329 330**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core 331 332**参数:** 333 334| 参数名 | 类型 | 必填 | 说明 | 335| ------ | ------------------------------------------ | ---- | ---------------------------- | 336| table | string | 是 | 指定的目标表名。 | 337| values | Array<[ValuesBucket](arkts-apis-data-relationalStore-t.md#valuesbucket)> | 是 | 表示要插入到表中的一组数据。| 338 339**返回值**: 340 341| 类型 | 说明 | 342| --------------------- | ----------------------------------------------------------- | 343| Promise<number> | Promise对象。如果操作成功,返回插入的数据个数,否则返回-1。 | 344 345**错误码:** 346 347以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)和[关系型数据库错误码](errorcode-data-rdb.md)。其中,14800011错误码处理可参考[数据库备份与恢复](../../database/data-backup-and-restore.md)。 348 349| **错误码ID** | **错误信息** | 350|-----------| ------------------------------------------------------------ | 351| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. | 352| 14800000 | Inner error. | 353| 14800011 | Failed to open the database because it is corrupted. | 354| 14800014 | The RdbStore or ResultSet is already closed. | 355| 14800021 | SQLite: Generic error. Possible causes: Insert failed or the updated data does not exist. | 356| 14800023 | SQLite: Access permission denied. | 357| 14800024 | SQLite: The database file is locked. | 358| 14800025 | SQLite: A table in the database is locked. | 359| 14800026 | SQLite: The database is out of memory. | 360| 14800027 | SQLite: Attempt to write a readonly database. | 361| 14800028 | SQLite: Some kind of disk I/O error occurred. | 362| 14800029 | SQLite: The database is full. | 363| 14800031 | SQLite: TEXT or BLOB exceeds size limit. | 364| 14800033 | SQLite: Data type mismatch. | 365| 14800047 | The WAL file size exceeds the default limit. | 366 367**示例:** 368 369```ts 370const valueBucket3: relationalStore.ValuesBucket = { 371 NAME: 'Lisa', 372 AGE: 18, 373 SALARY: 100.5, 374 CODES: new Uint8Array([1, 2, 3, 4, 5]) 375}; 376const valueBucket4: relationalStore.ValuesBucket = { 377 NAME: 'Jack', 378 AGE: 19, 379 SALARY: 101.5, 380 CODES: new Uint8Array([6, 7, 8, 9, 10]) 381}; 382const valueBucket5: relationalStore.ValuesBucket = { 383 NAME: 'Tom', 384 AGE: 20, 385 SALARY: 102.5, 386 CODES: new Uint8Array([11, 12, 13, 14, 15]) 387}; 388 389let valueBuckets = new Array(valueBucket3, valueBucket4, valueBucket5); 390if (store != undefined) { 391 try { 392 const transaction = await store.createTransaction(); 393 try { 394 const insertNum = await transaction.batchInsert('EMPLOYEE', valueBuckets); 395 await transaction.commit(); 396 console.info(`batchInsert is successful, the number of values that were inserted = ${insertNum}`); 397 } catch (error) { 398 const err = error as BusinessError; 399 await transaction.rollback(); 400 console.error(`batchInsert is failed, code is ${err.code},message is ${err.message}`); 401 } 402 } catch (error) { 403 const err = error as BusinessError; 404 console.error(`createTransaction failed, code is ${err.code},message is ${err.message}`); 405 } 406} 407``` 408 409## batchInsertSync<sup>14+</sup> 410 411batchInsertSync(table: string, values: Array<ValuesBucket>): number 412 413向目标表中插入一组数据。 414 415**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core 416 417**参数:** 418 419| 参数名 | 类型 | 必填 | 说明 | 420| ------ | ------------------------------------------ | ---- | ---------------------------- | 421| table | string | 是 | 指定的目标表名。 | 422| values | Array<[ValuesBucket](arkts-apis-data-relationalStore-t.md#valuesbucket)> | 是 | 表示要插入到表中的一组数据。 | 423 424**返回值**: 425 426| 类型 | 说明 | 427| ------ | ---------------------------------------------- | 428| number | 如果操作成功,返回插入的数据个数,否则返回-1。 | 429 430**错误码:** 431 432以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)和[关系型数据库错误码](errorcode-data-rdb.md)。其中,14800011错误码处理可参考[数据库备份与恢复](../../database/data-backup-and-restore.md)。 433 434| **错误码ID** | **错误信息** | 435| ------------ | ------------------------------------------------------------ | 436| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. | 437| 14800000 | Inner error. | 438| 14800011 | Failed to open the database because it is corrupted. | 439| 14800014 | The RdbStore or ResultSet is already closed. | 440| 14800021 | SQLite: Generic error. Possible causes: Insert failed or the updated data does not exist. | 441| 14800023 | SQLite: Access permission denied. | 442| 14800024 | SQLite: The database file is locked. | 443| 14800025 | SQLite: A table in the database is locked. | 444| 14800026 | SQLite: The database is out of memory. | 445| 14800027 | SQLite: Attempt to write a readonly database. | 446| 14800028 | SQLite: Some kind of disk I/O error occurred. | 447| 14800029 | SQLite: The database is full. | 448| 14800031 | SQLite: TEXT or BLOB exceeds size limit. | 449| 14800033 | SQLite: Data type mismatch. | 450| 14800047 | The WAL file size exceeds the default limit. | 451 452**示例:** 453 454```ts 455const valueBucket6: relationalStore.ValuesBucket = { 456 NAME: 'Lisa', 457 AGE: 18, 458 SALARY: 100.5, 459 CODES: new Uint8Array([1, 2, 3, 4, 5]) 460}; 461const valueBucket7: relationalStore.ValuesBucket = { 462 NAME: 'Jack', 463 AGE: 19, 464 SALARY: 101.5, 465 CODES: new Uint8Array([6, 7, 8, 9, 10]) 466}; 467const valueBucket8: relationalStore.ValuesBucket = { 468 NAME: 'Tom', 469 AGE: 20, 470 SALARY: 102.5, 471 CODES: new Uint8Array([11, 12, 13, 14, 15]) 472}; 473 474let valueBuckets2 = new Array(valueBucket6, valueBucket7, valueBucket8); 475if (store != undefined) { 476 try { 477 const transaction = await store.createTransaction(); 478 try { 479 let insertNum: number = (transaction as relationalStore.Transaction).batchInsertSync('EMPLOYEE', valueBuckets2); 480 await transaction.commit(); 481 console.info(`batchInsert is successful, the number of values that were inserted = ${insertNum}`); 482 } catch (error) { 483 const err = error as BusinessError; 484 await transaction.rollback(); 485 console.error(`batchInsert is failed, code is ${err.code},message is ${err.message}`); 486 } 487 } catch (error) { 488 const err = error as BusinessError; 489 console.error(`createTransaction failed, code is ${err.code},message is ${err.message}`); 490 } 491} 492``` 493 494## batchInsertWithConflictResolution<sup>18+</sup> 495 496batchInsertWithConflictResolution(table: string, values: Array<ValuesBucket>, conflict: ConflictResolution): Promise<number> 497 498向目标表中插入一组数据,使用Promise异步回调。 499 500**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core 501 502**参数:** 503 504| 参数名 | 类型 | 必填 | 说明 | 505| ------ | ------------------------------------------ | ---- | ---------------------------- | 506| table | string | 是 | 指定的目标表名。 | 507| values | Array<[ValuesBucket](arkts-apis-data-relationalStore-t.md#valuesbucket)> | 是 | 表示要插入到表中的一组数据。| 508| conflict | [ConflictResolution](arkts-apis-data-relationalStore-e.md#conflictresolution10)| 是 | 指定冲突解决模式。如果是ON_CONFLICT_ROLLBACK模式,当发生冲突时会回滚整个事务。 | 509 510**返回值**: 511 512| 类型 | 说明 | 513| --------------------- | ----------------------------------------------------------- | 514| Promise<number> | Promise对象。如果操作成功,返回插入的数据个数,否则返回-1。 | 515 516**错误码:** 517 518以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)和[关系型数据库错误码](errorcode-data-rdb.md)。其中,14800011错误码处理可参考[数据库备份与恢复](../../database/data-backup-and-restore.md)。 519 520| **错误码ID** | **错误信息** | 521|-----------| ------------------------------------------------------------ | 522| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. | 523| 14800000 | Inner error. | 524| 14800011 | Failed to open the database because it is corrupted. | 525| 14800014 | The RdbStore or ResultSet is already closed. | 526| 14800021 | SQLite: Generic error. Possible causes: Insert failed or the updated data does not exist. | 527| 14800022 | SQLite: Callback routine requested an abort. | 528| 14800023 | SQLite: Access permission denied. | 529| 14800024 | SQLite: The database file is locked. | 530| 14800025 | SQLite: A table in the database is locked. | 531| 14800026 | SQLite: The database is out of memory. | 532| 14800027 | SQLite: Attempt to write a readonly database. | 533| 14800028 | SQLite: Some kind of disk I/O error occurred. | 534| 14800029 | SQLite: The database is full. | 535| 14800031 | SQLite: TEXT or BLOB exceeds size limit. | 536| 14800032 | SQLite: Abort due to constraint violation. | 537| 14800033 | SQLite: Data type mismatch. | 538| 14800034 | SQLite: Library used incorrectly. | 539| 14800047 | The WAL file size exceeds the default limit. | 540 541**示例:** 542 543```ts 544const valueBucket9: relationalStore.ValuesBucket = { 545 NAME: 'Lisa', 546 AGE: 18, 547 SALARY: 100.5, 548 CODES: new Uint8Array([1, 2, 3, 4, 5]) 549}; 550const valueBucketA: relationalStore.ValuesBucket = { 551 NAME: 'Jack', 552 AGE: 19, 553 SALARY: 101.5, 554 CODES: new Uint8Array([6, 7, 8, 9, 10]) 555}; 556const valueBucketB: relationalStore.ValuesBucket = { 557 NAME: 'Tom', 558 AGE: 20, 559 SALARY: 102.5, 560 CODES: new Uint8Array([11, 12, 13, 14, 15]) 561}; 562 563let valueBuckets3 = new Array(valueBucket9, valueBucketA, valueBucketB); 564 565if (store != undefined) { 566 try { 567 const transaction = await store.createTransaction(); 568 try { 569 const insertNum = await transaction.batchInsertWithConflictResolution( 570 'EMPLOYEE', 571 valueBuckets3, 572 relationalStore.ConflictResolution.ON_CONFLICT_REPLACE 573 ); 574 await transaction.commit(); 575 console.info(`batchInsert is successful, the number of values that were inserted = ${insertNum}`); 576 } catch (error) { 577 const err = error as BusinessError; 578 await transaction.rollback(); 579 console.error(`batchInsert is failed, code is ${err.code},message is ${err.message}`); 580 } 581 } catch (error) { 582 const err = error as BusinessError; 583 console.error(`createTransaction failed, code is ${err.code},message is ${err.message}`); 584 } 585} 586``` 587 588## batchInsertWithConflictResolutionSync<sup>18+</sup> 589 590batchInsertWithConflictResolutionSync(table: string, values: Array<ValuesBucket>, conflict: ConflictResolution): number 591 592向目标表中插入一组数据。 593 594**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core 595 596**参数:** 597 598| 参数名 | 类型 | 必填 | 说明 | 599| ------ | ------------------------------------------ | ---- | ---------------------------- | 600| table | string | 是 | 指定的目标表名。 | 601| values | Array<[ValuesBucket](arkts-apis-data-relationalStore-t.md#valuesbucket)> | 是 | 表示要插入到表中的一组数据。 | 602| conflict | [ConflictResolution](arkts-apis-data-relationalStore-e.md#conflictresolution10)| 是 | 指定冲突解决模式。如果是ON_CONFLICT_ROLLBACK模式,当发生冲突时会回滚整个事务。 | 603 604**返回值**: 605 606| 类型 | 说明 | 607| ------ | ---------------------------------------------- | 608| number | 如果操作成功,返回插入的数据个数,否则返回-1。 | 609 610**错误码:** 611 612以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)和[关系型数据库错误码](errorcode-data-rdb.md)。其中,14800011错误码处理可参考[数据库备份与恢复](../../database/data-backup-and-restore.md)。 613 614| **错误码ID** | **错误信息** | 615| ------------ | ------------------------------------------------------------ | 616| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. | 617| 14800000 | Inner error. | 618| 14800011 | Failed to open the database because it is corrupted. | 619| 14800014 | The RdbStore or ResultSet is already closed. | 620| 14800021 | SQLite: Generic error. Possible causes: Insert failed or the updated data does not exist. | 621| 14800022 | SQLite: Callback routine requested an abort. | 622| 14800023 | SQLite: Access permission denied. | 623| 14800024 | SQLite: The database file is locked. | 624| 14800025 | SQLite: A table in the database is locked. | 625| 14800026 | SQLite: The database is out of memory. | 626| 14800027 | SQLite: Attempt to write a readonly database. | 627| 14800028 | SQLite: Some kind of disk I/O error occurred. | 628| 14800029 | SQLite: The database is full. | 629| 14800031 | SQLite: TEXT or BLOB exceeds size limit. | 630| 14800032 | SQLite: Abort due to constraint violation. | 631| 14800033 | SQLite: Data type mismatch. | 632| 14800034 | SQLite: Library used incorrectly. | 633| 14800047 | The WAL file size exceeds the default limit. | 634 635**示例:** 636 637```ts 638const valueBucketC: relationalStore.ValuesBucket = { 639 NAME: 'Lisa', 640 AGE: 18, 641 SALARY: 100.5, 642 CODES: new Uint8Array([1, 2, 3, 4, 5]) 643}; 644const valueBucketD: relationalStore.ValuesBucket = { 645 NAME: 'Jack', 646 AGE: 19, 647 SALARY: 101.5, 648 CODES: new Uint8Array([6, 7, 8, 9, 10]) 649}; 650const valueBucketE: relationalStore.ValuesBucket = { 651 NAME: 'Tom', 652 AGE: 20, 653 SALARY: 102.5, 654 CODES: new Uint8Array([11, 12, 13, 14, 15]) 655}; 656 657let valueBuckets4 = new Array(valueBucketC, valueBucketD, valueBucketE); 658if (store != undefined) { 659 try { 660 const transaction = await store.createTransaction(); 661 try { 662 const insertNum = transaction.batchInsertWithConflictResolutionSync( 663 'EMPLOYEE', 664 valueBuckets4, 665 relationalStore.ConflictResolution.ON_CONFLICT_REPLACE 666 ); 667 await transaction.commit(); 668 console.info(`batchInsert is successful, the number of values that were inserted = ${insertNum}`); 669 } catch (error) { 670 const err = error as BusinessError; 671 await transaction.rollback(); 672 console.error(`batchInsert is failed, code is ${err.code},message is ${err.message}`); 673 } 674 } catch (error) { 675 const err = error as BusinessError; 676 console.error(`createTransaction failed, code is ${err.code},message is ${err.message}`); 677 } 678} 679``` 680 681## update<sup>14+</sup> 682 683update(values: ValuesBucket, predicates: RdbPredicates, conflict?: ConflictResolution): Promise<number> 684 685根据RdbPredicates的指定实例对象更新数据库中的数据,使用Promise异步回调。由于共享内存大小限制为2Mb,因此单条数据的大小需小于2Mb,否则会查询失败。 686 687**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core 688 689**参数:** 690 691| 参数名 | 类型 | 必填 | 说明 | 692| ---------- | ------------------------------------------- | ---- | ------------------------------------------------------------ | 693| values | [ValuesBucket](arkts-apis-data-relationalStore-t.md#valuesbucket) | 是 | values指示数据库中要更新的数据行。键值对与数据库表的列名相关联。 | 694| predicates | [RdbPredicates](arkts-apis-data-relationalStore-RdbPredicates.md) | 是 | RdbPredicates的实例对象指定的更新条件。 | 695| conflict | [ConflictResolution](arkts-apis-data-relationalStore-e.md#conflictresolution10)| 否 | 指定冲突解决模式。默认值是relationalStore.ConflictResolution.ON_CONFLICT_NONE。 | 696 697**返回值**: 698 699| 类型 | 说明 | 700| --------------------- | ----------------------------------------- | 701| Promise<number> | 指定的Promise回调方法。返回受影响的行数。 | 702 703**错误码:** 704 705以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)和[关系型数据库错误码](errorcode-data-rdb.md)。其中,14800011错误码处理可参考[数据库备份与恢复](../../database/data-backup-and-restore.md)。 706 707| **错误码ID** | **错误信息** | 708|-----------| ------------------------------------------------------------ | 709| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. | 710| 14800000 | Inner error. | 711| 14800011 | Failed to open the database because it is corrupted. | 712| 14800014 | The RdbStore or ResultSet is already closed. | 713| 14800021 | SQLite: Generic error. Possible causes: Insert failed or the updated data does not exist. | 714| 14800023 | SQLite: Access permission denied. | 715| 14800024 | SQLite: The database file is locked. | 716| 14800025 | SQLite: A table in the database is locked. | 717| 14800026 | SQLite: The database is out of memory. | 718| 14800027 | SQLite: Attempt to write a readonly database. | 719| 14800028 | SQLite: Some kind of disk I/O error occurred. | 720| 14800029 | SQLite: The database is full. | 721| 14800031 | SQLite: TEXT or BLOB exceeds size limit. | 722| 14800033 | SQLite: Data type mismatch. | 723| 14800047 | The WAL file size exceeds the default limit. | 724 725**示例:** 726 727```ts 728const valueBucketF: relationalStore.ValuesBucket = { 729 NAME: 'Rose', 730 AGE: 22, 731 SALARY: 200.5, 732 CODES: new Uint8Array([1, 2, 3, 4, 5]) 733}; 734let predicates = new relationalStore.RdbPredicates('EMPLOYEE'); 735predicates.equalTo('NAME', 'Lisa'); 736 737if (store != undefined) { 738 try { 739 const transaction = await store.createTransaction(); 740 try { 741 const rows = await transaction.update(valueBucketF, predicates, relationalStore.ConflictResolution.ON_CONFLICT_REPLACE); 742 await transaction.commit(); 743 console.info(`Updated row count: ${rows}`); 744 } catch (error) { 745 const err = error as BusinessError; 746 await transaction.rollback(); 747 console.error(`Updated failed, code is ${err.code},message is ${err.message}`); 748 } 749 } catch (error) { 750 const err = error as BusinessError; 751 console.error(`createTransaction failed, code is ${err.code},message is ${err.message}`); 752 } 753} 754``` 755 756## updateSync<sup>14+</sup> 757 758updateSync(values: ValuesBucket, predicates: RdbPredicates, conflict?: ConflictResolution): number 759 760根据RdbPredicates的指定实例对象更新数据库中的数据。由于共享内存大小限制为2Mb,因此单条数据的大小需小于2Mb,否则会查询失败。 761 762**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core 763 764**参数:** 765 766| 参数名 | 类型 | 必填 | 说明 | 767| ---------- | ------------------------------------------- | ---- | ------------------------------------------------------------ | 768| values | [ValuesBucket](arkts-apis-data-relationalStore-t.md#valuesbucket) | 是 | values指示数据库中要更新的数据行。键值对与数据库表的列名相关联。 | 769| predicates | [RdbPredicates](arkts-apis-data-relationalStore-RdbPredicates.md) | 是 | RdbPredicates的实例对象指定的更新条件。 | 770| conflict | [ConflictResolution](arkts-apis-data-relationalStore-e.md#conflictresolution10)| 否 | 指定冲突解决模式。默认值是relationalStore.ConflictResolution.ON_CONFLICT_NONE。 | 771 772**返回值**: 773 774| 类型 | 说明 | 775| ------ | ------------------ | 776| number | 返回受影响的行数。 | 777 778**错误码:** 779 780以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)和[关系型数据库错误码](errorcode-data-rdb.md)。其中,14800011错误码处理可参考[数据库备份与恢复](../../database/data-backup-and-restore.md)。 781 782| **错误码ID** | **错误信息** | 783| ------------ | ------------------------------------------------------------ | 784| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. | 785| 14800000 | Inner error. | 786| 14800011 | Failed to open the database because it is corrupted. | 787| 14800014 | The RdbStore or ResultSet is already closed. | 788| 14800021 | SQLite: Generic error. Possible causes: Insert failed or the updated data does not exist. | 789| 14800023 | SQLite: Access permission denied. | 790| 14800024 | SQLite: The database file is locked. | 791| 14800025 | SQLite: A table in the database is locked. | 792| 14800026 | SQLite: The database is out of memory. | 793| 14800027 | SQLite: Attempt to write a readonly database. | 794| 14800028 | SQLite: Some kind of disk I/O error occurred. | 795| 14800029 | SQLite: The database is full. | 796| 14800031 | SQLite: TEXT or BLOB exceeds size limit. | 797| 14800033 | SQLite: Data type mismatch. | 798| 14800047 | The WAL file size exceeds the default limit. | 799 800**示例:** 801 802```ts 803const valueBucketG: relationalStore.ValuesBucket = { 804 NAME: 'Rose', 805 AGE: 22, 806 SALARY: 200.5, 807 CODES: new Uint8Array([1, 2, 3, 4, 5]) 808}; 809let predicates1 = new relationalStore.RdbPredicates('EMPLOYEE'); 810predicates1.equalTo('NAME', 'Lisa'); 811 812if (store != undefined) { 813 try { 814 const transaction = await store.createTransaction(); 815 try { 816 let rows = transaction.updateSync(valueBucketG, predicates1, relationalStore.ConflictResolution.ON_CONFLICT_REPLACE); 817 await transaction.commit(); 818 console.info(`Updated row count: ${rows}`); 819 } catch (error) { 820 const err = error as BusinessError; 821 await transaction.rollback(); 822 console.error(`Updated failed, code is ${err.code},message is ${err.message}`); 823 } 824 } catch (error) { 825 const err = error as BusinessError; 826 console.error(`createTransaction failed, code is ${err.code},message is ${err.message}`); 827 } 828} 829``` 830 831## delete<sup>14+</sup> 832 833delete(predicates: RdbPredicates):Promise<number> 834 835根据RdbPredicates的指定实例对象从数据库中删除数据,使用Promise异步回调。 836 837**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core 838 839**参数:** 840 841| 参数名 | 类型 | 必填 | 说明 | 842| ---------- | ------------------------------------ | ---- | ----------------------------------------- | 843| predicates | [RdbPredicates](arkts-apis-data-relationalStore-RdbPredicates.md) | 是 | RdbPredicates的实例对象指定的删除条件。 | 844 845**返回值**: 846 847| 类型 | 说明 | 848| --------------------- | ------------------------------- | 849| Promise<number> | Promise对象。返回受影响的行数。 | 850 851**错误码:** 852 853以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)和[关系型数据库错误码](errorcode-data-rdb.md)。其中,14800011错误码处理可参考[数据库备份与恢复](../../database/data-backup-and-restore.md)。 854 855| **错误码ID** | **错误信息** | 856|-----------| ------------------------------------------------------------ | 857| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. | 858| 14800000 | Inner error. | 859| 14800011 | Failed to open the database because it is corrupted. | 860| 14800014 | The RdbStore or ResultSet is already closed. | 861| 14800021 | SQLite: Generic error. Possible causes: Insert failed or the updated data does not exist. | 862| 14800023 | SQLite: Access permission denied. | 863| 14800024 | SQLite: The database file is locked. | 864| 14800025 | SQLite: A table in the database is locked. | 865| 14800026 | SQLite: The database is out of memory. | 866| 14800027 | SQLite: Attempt to write a readonly database. | 867| 14800028 | SQLite: Some kind of disk I/O error occurred. | 868| 14800029 | SQLite: The database is full. | 869| 14800031 | SQLite: TEXT or BLOB exceeds size limit. | 870| 14800033 | SQLite: Data type mismatch. | 871| 14800047 | The WAL file size exceeds the default limit. | 872 873**示例:** 874 875```ts 876let predicates2 = new relationalStore.RdbPredicates('EMPLOYEE'); 877predicates2.equalTo('NAME', 'Lisa'); 878 879if (store != undefined) { 880 try { 881 const transaction = await store.createTransaction(); 882 try { 883 const rows = await transaction.delete(predicates2); 884 await transaction.commit(); 885 console.info(`Delete rows: ${rows}`); 886 } catch (error) { 887 const err = error as BusinessError; 888 await transaction.rollback(); 889 console.error(`Delete failed, code is ${err.code},message is ${err.message}`); 890 } 891 } catch (error) { 892 const err = error as BusinessError; 893 console.error(`createTransaction failed, code is ${err.code},message is ${err.message}`); 894 } 895} 896``` 897 898## deleteSync<sup>14+</sup> 899 900deleteSync(predicates: RdbPredicates): number 901 902根据RdbPredicates的指定实例对象从数据库中删除数据。 903 904**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core 905 906**参数:** 907 908| 参数名 | 类型 | 必填 | 说明 | 909| ---------- | ------------------------------- | ---- | --------------------------------------- | 910| predicates | [RdbPredicates](arkts-apis-data-relationalStore-RdbPredicates.md) | 是 | RdbPredicates的实例对象指定的删除条件。 | 911 912**返回值**: 913 914| 类型 | 说明 | 915| ------ | ------------------ | 916| number | 返回受影响的行数。 | 917 918**错误码:** 919 920以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)和[关系型数据库错误码](errorcode-data-rdb.md)。其中,14800011错误码处理可参考[数据库备份与恢复](../../database/data-backup-and-restore.md)。 921 922| **错误码ID** | **错误信息** | 923| ------------ | ------------------------------------------------------------ | 924| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. | 925| 14800000 | Inner error. | 926| 14800011 | Failed to open the database because it is corrupted. | 927| 14800014 | The RdbStore or ResultSet is already closed. | 928| 14800021 | SQLite: Generic error. Possible causes: Insert failed or the updated data does not exist. | 929| 14800023 | SQLite: Access permission denied. | 930| 14800024 | SQLite: The database file is locked. | 931| 14800025 | SQLite: A table in the database is locked. | 932| 14800026 | SQLite: The database is out of memory. | 933| 14800027 | SQLite: Attempt to write a readonly database. | 934| 14800028 | SQLite: Some kind of disk I/O error occurred. | 935| 14800029 | SQLite: The database is full. | 936| 14800031 | SQLite: TEXT or BLOB exceeds size limit. | 937| 14800033 | SQLite: Data type mismatch. | 938| 14800047 | The WAL file size exceeds the default limit. | 939 940**示例:** 941 942```ts 943let predicates3 = new relationalStore.RdbPredicates('EMPLOYEE'); 944predicates3.equalTo('NAME', 'Lisa'); 945if (store != undefined) { 946 try { 947 const transaction = await store.createTransaction(); 948 try { 949 let rows = transaction.deleteSync(predicates3); 950 await transaction.commit(); 951 console.info(`Delete rows: ${rows}`); 952 } catch (error) { 953 const err = error as BusinessError; 954 await transaction.rollback(); 955 console.error(`Delete failed, code is ${err.code},message is ${err.message}`); 956 } 957 } catch (error) { 958 const err = error as BusinessError; 959 console.error(`createTransaction failed, code is ${err.code},message is ${err.message}`); 960 } 961} 962``` 963 964## query<sup>14+</sup> 965 966query(predicates: RdbPredicates, columns?: Array<string>): Promise<ResultSet> 967 968根据指定条件查询数据库中的数据,使用Promise异步回调。由于共享内存大小限制为2Mb,因此单条数据的大小需小于2Mb,否则会查询失败。 969 970**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core 971 972**参数:** 973 974| 参数名 | 类型 | 必填 | 说明 | 975| ---------- | ------------------------------------ | ---- | ------------------------------------------------ | 976| predicates | [RdbPredicates](arkts-apis-data-relationalStore-RdbPredicates.md) | 是 | RdbPredicates的实例对象指定的查询条件。 | 977| columns | Array<string> | 否 | 表示要查询的列。如果值为空,则查询应用于所有列。 | 978 979**返回值**: 980 981| 类型 | 说明 | 982| ------------------------------------------------------- | -------------------------------------------------- | 983| Promise<[ResultSet](arkts-apis-data-relationalStore-ResultSet.md)> | Promise对象。如果操作成功,则返回ResultSet对象。 | 984 985**错误码:** 986 987以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)和[关系型数据库错误码](errorcode-data-rdb.md)。 988 989| **错误码ID** | **错误信息** | 990|-----------| ------------------------------------------------------------ | 991| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. | 992| 14800000 | Inner error. | 993| 14800011 | Failed to open the database because it is corrupted. | 994| 14800014 | The RdbStore or ResultSet is already closed. | 995| 14800021 | SQLite: Generic error. Possible causes: Insert failed or the updated data does not exist. | 996| 14800023 | SQLite: Access permission denied. | 997| 14800024 | SQLite: The database file is locked. | 998| 14800026 | SQLite: The database is out of memory. | 999| 14800028 | SQLite: Some kind of disk I/O error occurred. | 1000| 14800047 | The WAL file size exceeds the default limit. | 1001 1002 1003**示例:** 1004 1005```ts 1006let predicates4 = new relationalStore.RdbPredicates('EMPLOYEE'); 1007predicates4.equalTo('NAME', 'Rose'); 1008 1009if (store != undefined) { 1010 try { 1011 const transaction = await store.createTransaction(); 1012 try { 1013 const resultSet = await transaction.query(predicates4, ['ID', 'NAME', 'AGE', 'SALARY', 'CODES']); 1014 console.info(`ResultSet column names: ${resultSet.columnNames}, column count: ${resultSet.columnCount}`); 1015 // resultSet是一个数据集合的游标,默认指向第-1个记录,有效的数据从0开始。 1016 while (resultSet.goToNextRow()) { 1017 const id = resultSet.getLong(resultSet.getColumnIndex('ID')); 1018 const name = resultSet.getString(resultSet.getColumnIndex('NAME')); 1019 const age = resultSet.getLong(resultSet.getColumnIndex('AGE')); 1020 const salary = resultSet.getDouble(resultSet.getColumnIndex('SALARY')); 1021 console.info(`id=${id}, name=${name}, age=${age}, salary=${salary}`); 1022 } 1023 // 释放数据集的内存,若不释放可能会引起fd泄露与内存泄露 1024 resultSet.close(); 1025 await transaction.commit(); 1026 } catch (error) { 1027 const err = error as BusinessError; 1028 await transaction.rollback(); 1029 console.error(`Query failed, code is ${err.code},message is ${err.message}`); 1030 } 1031 } catch (error) { 1032 const err = error as BusinessError; 1033 console.error(`createTransaction failed, code is ${err.code},message is ${err.message}`); 1034 } 1035} 1036``` 1037 1038## querySync<sup>14+</sup> 1039 1040querySync(predicates: RdbPredicates, columns?: Array<string>): ResultSet 1041 1042根据指定条件查询数据库中的数据。对query同步接口获得的resultSet进行操作时,若逻辑复杂且循环次数过多,可能造成freeze问题,建议将此步骤放到[taskpool](../apis-arkts/js-apis-taskpool.md)线程中执行。 1043 1044**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core 1045 1046**参数:** 1047 1048| 参数名 | 类型 | 必填 | 说明 | 1049| ---------- | ------------------------------- | ---- | ------------------------------------------------------------ | 1050| predicates | [RdbPredicates](arkts-apis-data-relationalStore-RdbPredicates.md) | 是 | RdbPredicates的实例对象指定的查询条件。 | 1051| columns | Array<string> | 否 | 表示要查询的列。如果值为空,则查询应用于所有列。默认值为空。 | 1052 1053**返回值**: 1054 1055| 类型 | 说明 | 1056| ----------------------- | ----------------------------------- | 1057| [ResultSet](arkts-apis-data-relationalStore-ResultSet.md) | 如果操作成功,则返回ResultSet对象。 | 1058 1059**错误码:** 1060 1061以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)和[关系型数据库错误码](errorcode-data-rdb.md)。 1062 1063| **错误码ID** | **错误信息** | 1064| ------------ | ------------------------------------------------------------ | 1065| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. | 1066| 14800000 | Inner error. | 1067| 14800011 | Failed to open the database because it is corrupted. | 1068| 14800014 | The RdbStore or ResultSet is already closed. | 1069| 14800021 | SQLite: Generic error. Possible causes: Insert failed or the updated data does not exist. | 1070| 14800023 | SQLite: Access permission denied. | 1071| 14800024 | SQLite: The database file is locked. | 1072| 14800025 | SQLite: A table in the database is locked. | 1073| 14800026 | SQLite: The database is out of memory. | 1074| 14800028 | SQLite: Some kind of disk I/O error occurred. | 1075| 14800047 | The WAL file size exceeds the default limit. | 1076 1077**示例:** 1078 1079```ts 1080let predicates5 = new relationalStore.RdbPredicates('EMPLOYEE'); 1081predicates5.equalTo('NAME', 'Rose'); 1082 1083if (store != undefined) { 1084 try { 1085 const transaction = await store.createTransaction(); 1086 try { 1087 let resultSet = transaction.querySync(predicates5, ['ID', 'NAME', 'AGE', 'SALARY', 'CODES']); 1088 console.info(`ResultSet column names: ${resultSet.columnNames}, column count: ${resultSet.columnCount}`); 1089 // resultSet是一个数据集合的游标,默认指向第-1个记录,有效的数据从0开始。 1090 while (resultSet.goToNextRow()) { 1091 const id = resultSet.getLong(resultSet.getColumnIndex('ID')); 1092 const name = resultSet.getString(resultSet.getColumnIndex('NAME')); 1093 const age = resultSet.getLong(resultSet.getColumnIndex('AGE')); 1094 const salary = resultSet.getDouble(resultSet.getColumnIndex('SALARY')); 1095 console.info(`id=${id}, name=${name}, age=${age}, salary=${salary}`); 1096 } 1097 // 释放数据集的内存,若不释放可能会引起fd泄露与内存泄露 1098 resultSet.close(); 1099 await transaction.commit(); 1100 } catch (error) { 1101 const err = error as BusinessError; 1102 await transaction.rollback(); 1103 console.error(`Query failed, code is ${err.code},message is ${err.message}`); 1104 } 1105 } catch (error) { 1106 const err = error as BusinessError; 1107 console.error(`createTransaction failed, code is ${err.code},message is ${err.message}`); 1108 } 1109} 1110``` 1111 1112## querySql<sup>14+</sup> 1113 1114querySql(sql: string, args?: Array<ValueType>): Promise<ResultSet> 1115 1116根据指定SQL语句查询数据库中的数据,SQL语句中的各种表达式和操作符之间的关系操作符号不超过1000个,使用Promise异步回调。 1117 1118**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core 1119 1120**参数:** 1121 1122| 参数名 | 类型 | 必填 | 说明 | 1123| -------- | ------------------------------------ | ---- | ------------------------------------------------------------ | 1124| sql | string | 是 | 指定要执行的SQL语句。 | 1125| args | Array<[ValueType](arkts-apis-data-relationalStore-t.md#valuetype)> | 否 | SQL语句中参数的值。该值与sql参数语句中的占位符相对应。当sql参数语句完整时,该参数不填。 | 1126 1127**返回值**: 1128 1129| 类型 | 说明 | 1130| ------------------------------------------------------- | -------------------------------------------------- | 1131| Promise<[ResultSet](arkts-apis-data-relationalStore-ResultSet.md)> | Promise对象。如果操作成功,则返回ResultSet对象。 | 1132 1133**错误码:** 1134 1135以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)和[关系型数据库错误码](errorcode-data-rdb.md)。 1136 1137| **错误码ID** | **错误信息** | 1138|-----------| ------------------------------------------------------------ | 1139| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. | 1140| 14800000 | Inner error. | 1141| 14800011 | Failed to open the database because it is corrupted. | 1142| 14800014 | The RdbStore or ResultSet is already closed. | 1143| 14800021 | SQLite: Generic error. Possible causes: Insert failed or the updated data does not exist. | 1144| 14800023 | SQLite: Access permission denied. | 1145| 14800024 | SQLite: The database file is locked. | 1146| 14800025 | SQLite: A table in the database is locked. | 1147| 14800026 | SQLite: The database is out of memory. | 1148| 14800028 | SQLite: Some kind of disk I/O error occurred. | 1149| 14800047 | The WAL file size exceeds the default limit. | 1150 1151**示例:** 1152 1153```ts 1154if (store != undefined) { 1155 try { 1156 const transaction = await store.createTransaction(); 1157 try { 1158 const resultSet = await transaction.querySql("SELECT * FROM EMPLOYEE CROSS JOIN BOOK WHERE BOOK.NAME = 'sanguo'"); 1159 console.info(`ResultSet column names: ${resultSet.columnNames}, column count: ${resultSet.columnCount}`); 1160 // resultSet是一个数据集合的游标,默认指向第-1个记录,有效的数据从0开始。 1161 while (resultSet.goToNextRow()) { 1162 const id = resultSet.getLong(resultSet.getColumnIndex('ID')); 1163 const name = resultSet.getString(resultSet.getColumnIndex('NAME')); 1164 const age = resultSet.getLong(resultSet.getColumnIndex('AGE')); 1165 const salary = resultSet.getDouble(resultSet.getColumnIndex('SALARY')); 1166 console.info(`id=${id}, name=${name}, age=${age}, salary=${salary}`); 1167 } 1168 // 释放数据集的内存,若不释放可能会引起fd泄露与内存泄露 1169 resultSet.close(); 1170 await transaction.commit(); 1171 } catch (error) { 1172 const err = error as BusinessError; 1173 await transaction.rollback(); 1174 console.error(`Query failed, code is ${err.code},message is ${err.message}`); 1175 } 1176 } catch (error) { 1177 const err = error as BusinessError; 1178 console.error(`createTransaction failed, code is ${err.code},message is ${err.message}`); 1179 } 1180} 1181``` 1182 1183## querySqlSync<sup>14+</sup> 1184 1185querySqlSync(sql: string, args?: Array<ValueType>): ResultSet 1186 1187根据指定SQL语句查询数据库中的数据,SQL语句中的各种表达式和操作符之间的关系操作符号不超过1000个。对query同步接口获得的resultSet进行操作时,若逻辑复杂且循环次数过多,可能造成freeze问题,建议将此步骤放到[taskpool](../apis-arkts/js-apis-taskpool.md)线程中执行。 1188 1189**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core 1190 1191**参数:** 1192 1193| 参数名 | 类型 | 必填 | 说明 | 1194| -------- | ------------------------------------ | ---- | ------------------------------------------------------------ | 1195| sql | string | 是 | 指定要执行的SQL语句。 | 1196| args | Array<[ValueType](arkts-apis-data-relationalStore-t.md#valuetype)> | 否 | SQL语句中参数的值。该值与sql参数语句中的占位符相对应。当sql参数语句完整时,该参数不填。默认值为空。 | 1197 1198**返回值**: 1199 1200| 类型 | 说明 | 1201| ----------------------- | ----------------------------------- | 1202| [ResultSet](arkts-apis-data-relationalStore-ResultSet.md) | 如果操作成功,则返回ResultSet对象。 | 1203 1204**错误码:** 1205 1206以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)和[关系型数据库错误码](errorcode-data-rdb.md)。 1207 1208| **错误码ID** | **错误信息** | 1209| ------------ | ------------------------------------------------------------ | 1210| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. | 1211| 14800000 | Inner error. | 1212| 14800011 | Failed to open the database because it is corrupted. | 1213| 14800014 | The RdbStore or ResultSet is already closed. | 1214| 14800021 | SQLite: Generic error. Possible causes: Insert failed or the updated data does not exist. | 1215| 14800023 | SQLite: Access permission denied. | 1216| 14800024 | SQLite: The database file is locked. | 1217| 14800025 | SQLite: A table in the database is locked. | 1218| 14800026 | SQLite: The database is out of memory. | 1219| 14800028 | SQLite: Some kind of disk I/O error occurred. | 1220| 14800047 | The WAL file size exceeds the default limit. | 1221 1222**示例:** 1223 1224```ts 1225if (store != undefined) { 1226 try { 1227 const transaction = await store.createTransaction(); 1228 try { 1229 let resultSet = transaction.querySqlSync("SELECT * FROM EMPLOYEE CROSS JOIN BOOK WHERE BOOK.NAME = 'sanguo'"); 1230 console.info(`ResultSet column names: ${resultSet.columnNames}, column count: ${resultSet.columnCount}`); 1231 // resultSet是一个数据集合的游标,默认指向第-1个记录,有效的数据从0开始。 1232 while (resultSet.goToNextRow()) { 1233 const id = resultSet.getLong(resultSet.getColumnIndex('ID')); 1234 const name = resultSet.getString(resultSet.getColumnIndex('NAME')); 1235 const age = resultSet.getLong(resultSet.getColumnIndex('AGE')); 1236 const salary = resultSet.getDouble(resultSet.getColumnIndex('SALARY')); 1237 console.info(`id=${id}, name=${name}, age=${age}, salary=${salary}`); 1238 } 1239 // 释放数据集的内存,若不释放可能会引起fd泄露与内存泄露 1240 resultSet.close(); 1241 await transaction.commit(); 1242 } catch (error) { 1243 const err = error as BusinessError; 1244 await transaction.rollback(); 1245 console.error(`Query failed, code is ${err.code},message is ${err.message}`); 1246 } 1247 } catch (error) { 1248 const err = error as BusinessError; 1249 console.error(`createTransaction failed, code is ${err.code},message is ${err.message}`); 1250 } 1251} 1252``` 1253 1254## execute<sup>14+</sup> 1255 1256execute(sql: string, args?: Array<ValueType>): Promise<ValueType> 1257 1258执行包含指定参数的SQL语句,语句中的各种表达式和操作符之间的关系操作符号不超过1000个,返回值类型为ValueType,使用Promise异步回调。 1259 1260该接口支持执行增删改操作,支持执行PRAGMA语法的sql,支持对表的操作(建表、删表、修改表),返回结果类型由执行具体sql的结果决定。 1261 1262此接口不支持执行查询、附加数据库和事务操作,查询可以使用[querySql](#querysql14)、[query](#query14)接口代替、附加数据库可以使用[attach](arkts-apis-data-relationalStore-RdbStore.md#attach12)接口代替。 1263 1264不支持分号分隔的多条语句。 1265 1266**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core 1267 1268**参数:** 1269 1270| 参数名 | 类型 | 必填 | 说明 | 1271| -------- | ------------------------------------ | ---- | ------------------------------------------------------------ | 1272| sql | string | 是 | 指定要执行的SQL语句。 | 1273| args | Array<[ValueType](arkts-apis-data-relationalStore-t.md#valuetype)> | 否 | SQL语句中参数的值。该值与sql参数语句中的占位符相对应。当sql参数语句完整时,该参数不填。 | 1274 1275**返回值**: 1276 1277| 类型 | 说明 | 1278| ------------------- | ------------------------- | 1279| Promise<[ValueType](arkts-apis-data-relationalStore-t.md#valuetype)> | Promise对象,返回sql执行后的结果。 | 1280 1281**错误码:** 1282 1283以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)和[关系型数据库错误码](errorcode-data-rdb.md)。其中,14800011错误码处理可参考[数据库备份与恢复](../../database/data-backup-and-restore.md)。 1284 1285| **错误码ID** | **错误信息** | 1286|-----------| ------------------------------------------------------------ | 1287| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. | 1288| 801 | Capability not supported the sql(attach,begin,commit,rollback etc.). | 1289| 14800000 | Inner error. | 1290| 14800011 | Failed to open the database because it is corrupted. | 1291| 14800014 | The RdbStore or ResultSet is already closed. | 1292| 14800021 | SQLite: Generic error. Possible causes: Insert failed or the updated data does not exist. | 1293| 14800023 | SQLite: Access permission denied. | 1294| 14800024 | SQLite: The database file is locked. | 1295| 14800025 | SQLite: A table in the database is locked. | 1296| 14800026 | SQLite: The database is out of memory. | 1297| 14800027 | SQLite: Attempt to write a readonly database. | 1298| 14800028 | SQLite: Some kind of disk I/O error occurred. | 1299| 14800029 | SQLite: The database is full. | 1300| 14800031 | SQLite: TEXT or BLOB exceeds size limit. | 1301| 14800033 | SQLite: Data type mismatch. | 1302| 14800047 | The WAL file size exceeds the default limit. | 1303 1304**示例:** 1305 1306```ts 1307if (store != undefined) { 1308 try { 1309 const transaction = await store.createTransaction(); 1310 try { 1311 // 删除表中所有数据 1312 const SQL_DELETE_TABLE = 'DELETE FROM EMPLOYEE'; 1313 const data = await transaction.execute(SQL_DELETE_TABLE); 1314 await transaction.commit(); 1315 console.info(`delete result: ${data}`); 1316 } catch (error) { 1317 const err = error as BusinessError; 1318 await transaction.rollback(); 1319 console.error(`delete failed, code is ${err.code}, message is ${err.message}`); 1320 } 1321 } catch (error) { 1322 const err = error as BusinessError; 1323 console.error(`createTransaction failed, code is ${err.code},message is ${err.message}`); 1324 } 1325} 1326``` 1327 1328## executeSync<sup>14+</sup> 1329 1330executeSync(sql: string, args?: Array<ValueType>): ValueType 1331 1332执行包含指定参数的SQL语句,语句中的各种表达式和操作符之间的关系操作符号不超过1000个,返回值类型为ValueType。 1333 1334该接口支持执行增删改操作,支持执行PRAGMA语法的sql,支持对表的操作(建表、删表、修改表),返回结果类型由执行具体sql的结果决定。 1335 1336此接口不支持执行查询、附加数据库和事务操作,查询可以使用[querySql](#querysql14)、[query](#query14)接口代替、附加数据库可以使用[attach](arkts-apis-data-relationalStore-RdbStore.md#attach12)接口代替。 1337 1338不支持分号分隔的多条语句。 1339 1340**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core 1341 1342**参数:** 1343 1344| 参数名 | 类型 | 必填 | 说明 | 1345| ------ | ------------------------------------ | ---- | ------------------------------------------------------------ | 1346| sql | string | 是 | 指定要执行的SQL语句。 | 1347| args | Array<[ValueType](arkts-apis-data-relationalStore-t.md#valuetype)> | 否 | SQL语句中参数的值。该值与sql参数语句中的占位符相对应。该参数不填,或者填null或undefined,都认为是sql参数语句完整。默认值为空。 | 1348 1349**返回值**: 1350 1351| 类型 | 说明 | 1352| ----------------------- | ------------------- | 1353| [ValueType](arkts-apis-data-relationalStore-t.md#valuetype) | 返回sql执行后的结果。 | 1354 1355**错误码:** 1356 1357以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)和[关系型数据库错误码](errorcode-data-rdb.md)。其中,14800011错误码处理可参考[数据库备份与恢复](../../database/data-backup-and-restore.md)。 1358 1359| **错误码ID** | **错误信息** | 1360| ------------ | ------------------------------------------------------------ | 1361| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. | 1362| 801 | Capability not supported the sql(attach,begin,commit,rollback etc.). | 1363| 14800000 | Inner error. | 1364| 14800011 | Failed to open the database because it is corrupted. | 1365| 14800014 | The RdbStore or ResultSet is already closed. | 1366| 14800021 | SQLite: Generic error. Possible causes: Insert failed or the updated data does not exist. | 1367| 14800023 | SQLite: Access permission denied. | 1368| 14800024 | SQLite: The database file is locked. | 1369| 14800025 | SQLite: A table in the database is locked. | 1370| 14800026 | SQLite: The database is out of memory. | 1371| 14800027 | SQLite: Attempt to write a readonly database. | 1372| 14800028 | SQLite: Some kind of disk I/O error occurred. | 1373| 14800029 | SQLite: The database is full. | 1374| 14800031 | SQLite: TEXT or BLOB exceeds size limit. | 1375| 14800033 | SQLite: Data type mismatch. | 1376| 14800047 | The WAL file size exceeds the default limit. | 1377 1378**示例:** 1379 1380```ts 1381// 删除表中所有数据 1382if (store != undefined) { 1383 try { 1384 const transaction = await store.createTransaction(); 1385 try { 1386 const SQL_DELETE_TABLE = 'DELETE FROM EMPLOYEE'; 1387 let data = transaction.executeSync(SQL_DELETE_TABLE); 1388 await transaction.commit(); 1389 console.info(`delete result: ${data}`); 1390 } catch (error) { 1391 const err = error as BusinessError; 1392 await transaction.rollback(); 1393 console.error(`delete failed, code is ${err.code}, message is ${err.message}`); 1394 } 1395 } catch (error) { 1396 const err = error as BusinessError; 1397 console.error(`createTransaction failed, code is ${err.code},message is ${err.message}`); 1398 } 1399} 1400```