1# Interface (Transaction) 2 3> **NOTE** 4> 5> - The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. 6> 7> - The initial APIs of this module are supported since API version 14. 8 9Provides APIs for managing databases in transaction mode. A transaction object is created by using [createTransaction](arkts-apis-data-relationalStore-RdbStore.md#createtransaction14). Operations on different transaction objects are isolated. For details about the transaction types, see [TransactionType](arkts-apis-data-relationalStore-e.md#transactiontype14). 10 11Currently, an RDB store supports only one write transaction at a time. If the current [RdbStore](arkts-apis-data-relationalStore-RdbStore.md) has a write transaction that is not released, creating an **IMMEDIATE** or **EXCLUSIVE** transaction object will return error 14800024. If a **DEFERRED** transaction object is created, error 14800024 may be returned when it is used to invoke a write operation for the first time. After a write transaction is created using **IMMEDIATE** or **EXCLUSIVE**, or a **DEFERRED** transaction is upgraded to a write transaction, write operations in the [RdbStore](arkts-apis-data-relationalStore-RdbStore.md) will also return error 14800024. 12 13When the number of concurrent transactions is large and the write transaction duration is long, the frequency of returning error 14800024 may increase. You can reduce the occurrence of error 14800024 by shortening the transaction duration or by handling the error 14800024 through retries. 14 15Before using the following APIs, you should obtain a **Transaction** instance by calling the [createTransaction](./arkts-apis-data-relationalStore-RdbStore.md#createtransaction14) method and then call the corresponding method through the instance. 16 17**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core 18 19**Example**: 20 21```ts 22import { UIAbility } from '@kit.AbilityKit'; 23import { BusinessError } from '@kit.BasicServicesKit'; 24import { window } from '@kit.ArkUI'; 25 26let store: relationalStore.RdbStore | undefined = undefined; 27 28class EntryAbility extends UIAbility { 29 async onWindowStageCreate(windowStage: window.WindowStage) { 30 const STORE_CONFIG: relationalStore.StoreConfig = { 31 name: "RdbTest.db", 32 securityLevel: relationalStore.SecurityLevel.S3 33 }; 34 35 await relationalStore.getRdbStore(this.context, STORE_CONFIG).then(async (rdbStore: relationalStore.RdbStore) => { 36 store = rdbStore; 37 console.info('Get RdbStore successfully.'); 38 }).catch((err: BusinessError) => { 39 console.error(`Get RdbStore failed, code is ${err.code},message is ${err.message}`); 40 }); 41 42 if (store != undefined) { 43 (store as relationalStore.RdbStore).createTransaction().then((transaction: relationalStore.Transaction) => { 44 console.info(`createTransaction success`); 45 // Perform subsequent operations after the transaction instance is successfully obtained. 46 }).catch((err: BusinessError) => { 47 console.error(`createTransaction failed, code is ${err.code},message is ${err.message}`); 48 }); 49 } 50 } 51} 52``` 53 54## Module to Import 55 56```ts 57import { relationalStore } from '@kit.ArkData'; 58``` 59 60## commit<sup>14+</sup> 61 62commit(): Promise<void> 63 64Commits the executed SQL statements. When using asynchronous APIs to execute SQL statements, ensure that **commit()** is called after the asynchronous API execution is completed. Otherwise, the SQL operations may be lost. After **commit()** is called, the transaction object and the created **ResultSet** object will be closed. 65 66**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core 67 68**Return value** 69 70| Type | Description | 71| ------------------- | ------------------------- | 72| Promise<void> | Promise that returns no value.| 73 74**Error codes** 75 76For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [RDB Store Error Codes](errorcode-data-rdb.md). For details about how to handle error 14800011, see [Database Backup and Restore](../../database/data-backup-and-restore.md). 77 78| **ID**| **Error Message** | 79|-----------| ------------------------------------------------------------ | 80| 14800000 | Inner error. | 81| 14800011 | Failed to open the database because it is corrupted. | 82| 14800014 | The RdbStore or ResultSet is already closed. | 83| 14800023 | SQLite: Access permission denied. | 84| 14800024 | SQLite: The database file is locked. | 85| 14800026 | SQLite: The database is out of memory. | 86| 14800027 | SQLite: Attempt to write a readonly database. | 87| 14800028 | SQLite: Some kind of disk I/O error occurred. | 88| 14800029 | SQLite: The database is full. | 89 90**Example**: 91 92```ts 93let value1 = "Lisa"; 94let value2 = 18; 95let value3 = 100.5; 96let value4 = new Uint8Array([1, 2, 3]); 97 98if (store != undefined) { 99 const valueBucket: relationalStore.ValuesBucket = { 100 'NAME': value1, 101 'AGE': value2, 102 'SALARY': value3, 103 'CODES': value4 104 }; 105 (store as relationalStore.RdbStore).createTransaction().then((transaction: relationalStore.Transaction) => { 106 transaction.execute("DELETE FROM TEST WHERE age = ? OR age = ?", ["18", "20"]).then(() => { 107 transaction.commit(); 108 }).catch((e: BusinessError) => { 109 transaction.rollback(); 110 console.error(`execute sql failed, code is ${e.code},message is ${e.message}`); 111 }); 112 }).catch((err: BusinessError) => { 113 console.error(`createTransaction failed, code is ${err.code},message is ${err.message}`); 114 }); 115} 116``` 117 118## rollback<sup>14+</sup> 119 120rollback(): Promise<void> 121 122Rolls back the SQL statements that have been executed. After **rollback()** is called, the transaction object and the created **ResultSet** object will be closed. 123 124**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core 125 126**Return value** 127 128| Type | Description | 129| ------------------- | ------------------------- | 130| Promise<void> | Promise that returns no value.| 131 132**Error codes** 133 134For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [RDB Store Error Codes](errorcode-data-rdb.md). For details about how to handle error 14800011, see [Database Backup and Restore](../../database/data-backup-and-restore.md). 135 136| **ID**| **Error Message** | 137|-----------| ------------------------------------------------------------ | 138| 14800000 | Inner error. | 139| 14800011 | Failed to open the database because it is corrupted. | 140| 14800014 | The RdbStore or ResultSet is already closed. | 141| 14800023 | SQLite: Access permission denied. | 142| 14800024 | SQLite: The database file is locked. | 143| 14800026 | SQLite: The database is out of memory. | 144| 14800027 | SQLite: Attempt to write a readonly database. | 145| 14800028 | SQLite: Some kind of disk I/O error occurred. | 146| 14800029 | SQLite: The database is full. | 147 148**Example**: 149 150```ts 151if (store != undefined) { 152 (store as relationalStore.RdbStore).createTransaction().then((transaction: relationalStore.Transaction) => { 153 transaction.execute("DELETE FROM TEST WHERE age = ? OR age = ?", ["18", "20"]).then(() => { 154 transaction.commit(); 155 }).catch((e: BusinessError) => { 156 transaction.rollback(); 157 console.error(`execute sql failed, code is ${e.code},message is ${e.message}`); 158 }); 159 }).catch((err: BusinessError) => { 160 console.error(`createTransaction failed, code is ${err.code},message is ${err.message}`); 161 }); 162} 163``` 164 165## insert<sup>14+</sup> 166 167insert(table: string, values: ValuesBucket, conflict?: ConflictResolution): Promise<number> 168 169Inserts a row of data into a table. This API uses a promise to return the result. Due to the limit of the shared memory (max. 2 MB), a single data record cannot exceed 2 MB. Otherwise, the query operation will fail. 170 171**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core 172 173**Parameters** 174 175| Name | Type | Mandatory| Description | 176| -------- | ------------------------------------------- | ---- | -------------------------- | 177| table | string | Yes | Name of the target table. | 178| values | [ValuesBucket](arkts-apis-data-relationalStore-t.md#valuesbucket) | Yes | Row of data to insert.| 179| conflict | [ConflictResolution](arkts-apis-data-relationalStore-e.md#conflictresolution10)| No | Resolution used to resolve the conflict. <br>Default value: **relationalStore.ConflictResolution.ON_CONFLICT_NONE**. | 180 181**Return value** 182 183| Type | Description | 184| --------------------- | ------------------------------------------------- | 185| Promise<number> | Promise used to return the result. If the operation is successful, the row ID will be returned. Otherwise, **-1** will be returned.| 186 187**Error codes** 188 189For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [RDB Store Error Codes](errorcode-data-rdb.md). For details about how to handle error 14800011, see [Database Backup and Restore](../../database/data-backup-and-restore.md). 190 191| **ID**| **Error Message** | 192|-----------| ------------------------------------------------------------ | 193| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. | 194| 14800000 | Inner error. | 195| 14800011 | Failed to open the database because it is corrupted. | 196| 14800014 | The RdbStore or ResultSet is already closed. | 197| 14800021 | SQLite: Generic error. Possible causes: Insert failed or the updated data does not exist. | 198| 14800023 | SQLite: Access permission denied. | 199| 14800024 | SQLite: The database file is locked. | 200| 14800025 | SQLite: A table in the database is locked. | 201| 14800026 | SQLite: The database is out of memory. | 202| 14800027 | SQLite: Attempt to write a readonly database. | 203| 14800028 | SQLite: Some kind of disk I/O error occurred. | 204| 14800029 | SQLite: The database is full. | 205| 14800031 | SQLite: TEXT or BLOB exceeds size limit. | 206| 14800033 | SQLite: Data type mismatch. | 207| 14800047 | The WAL file size exceeds the default limit. | 208 209**Example**: 210 211```ts 212let value1 = "Lisa"; 213let value2 = 18; 214let value3 = 100.5; 215let value4 = new Uint8Array([1, 2, 3, 4, 5]); 216 217// You can use either of the following: 218const valueBucket1: relationalStore.ValuesBucket = { 219 'NAME': value1, 220 'AGE': value2, 221 'SALARY': value3, 222 'CODES': value4 223}; 224const valueBucket2: relationalStore.ValuesBucket = { 225 NAME: value1, 226 AGE: value2, 227 SALARY: value3, 228 CODES: value4 229}; 230const valueBucket3: relationalStore.ValuesBucket = { 231 "NAME": value1, 232 "AGE": value2, 233 "SALARY": value3, 234 "CODES": value4 235}; 236 237if (store != undefined) { 238 (store as relationalStore.RdbStore).createTransaction().then((transaction: relationalStore.Transaction) => { 239 transaction.insert("EMPLOYEE", valueBucket1, relationalStore.ConflictResolution.ON_CONFLICT_REPLACE).then((rowId: number) => { 240 transaction.commit(); 241 console.info(`Insert is successful, rowId = ${rowId}`); 242 }).catch((e: BusinessError) => { 243 transaction.rollback(); 244 console.error(`Insert is failed, code is ${e.code},message is ${e.message}`); 245 }); 246 }).catch((err: BusinessError) => { 247 console.error(`createTransaction failed, code is ${err.code},message is ${err.message}`); 248 }); 249} 250``` 251 252## insertSync<sup>14+</sup> 253 254insertSync(table: string, values: ValuesBucket | sendableRelationalStore.ValuesBucket, conflict?: ConflictResolution): number 255 256Inserts a row of data into a table. This API returns the result synchronously. Due to the limit of the shared memory (max. 2 MB), a single data record cannot exceed 2 MB. Otherwise, the query operation will fail. 257 258**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core 259 260**Parameters** 261 262| Name | Type | Mandatory| Description | 263| -------- | ------------------------------------------- | ---- | ------------------------------------------------------------ | 264| table | string | Yes | Name of the target table. | 265| values | [ValuesBucket](arkts-apis-data-relationalStore-t.md#valuesbucket) \| [sendableRelationalStore.ValuesBucket](./js-apis-data-sendableRelationalStore.md#valuesbucket) | Yes | Row of data to insert. | 266| conflict | [ConflictResolution](arkts-apis-data-relationalStore-e.md#conflictresolution10)| No | Resolution used to resolve the conflict. <br>Default value: **relationalStore.ConflictResolution.ON_CONFLICT_NONE**.| 267 268**Return value** 269 270| Type | Description | 271| ------ | ------------------------------------ | 272| number | If the operation is successful, the row ID will be returned. Otherwise, **-1** will be returned.| 273 274**Error codes** 275 276For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [RDB Store Error Codes](errorcode-data-rdb.md). For details about how to handle error 14800011, see [Database Backup and Restore](../../database/data-backup-and-restore.md). 277 278| **ID**| **Error Message** | 279| ------------ | ------------------------------------------------------------ | 280| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. | 281| 14800000 | Inner error. | 282| 14800011 | Failed to open the database because it is corrupted. | 283| 14800014 | The RdbStore or ResultSet is already closed. | 284| 14800021 | SQLite: Generic error. Possible causes: Insert failed or the updated data does not exist. | 285| 14800023 | SQLite: Access permission denied. | 286| 14800024 | SQLite: The database file is locked. | 287| 14800025 | SQLite: A table in the database is locked. | 288| 14800026 | SQLite: The database is out of memory. | 289| 14800027 | SQLite: Attempt to write a readonly database. | 290| 14800028 | SQLite: Some kind of disk I/O error occurred. | 291| 14800029 | SQLite: The database is full. | 292| 14800031 | SQLite: TEXT or BLOB exceeds size limit. | 293| 14800033 | SQLite: Data type mismatch. | 294| 14800047 | The WAL file size exceeds the default limit. | 295 296**Example**: 297 298```ts 299let value1 = "Lisa"; 300let value2 = 18; 301let value3 = 100.5; 302let value4 = new Uint8Array([1, 2, 3, 4, 5]); 303 304// You can use either of the following: 305const valueBucket1: relationalStore.ValuesBucket = { 306 'NAME': value1, 307 'AGE': value2, 308 'SALARY': value3, 309 'CODES': value4 310}; 311const valueBucket2: relationalStore.ValuesBucket = { 312 NAME: value1, 313 AGE: value2, 314 SALARY: value3, 315 CODES: value4 316}; 317const valueBucket3: relationalStore.ValuesBucket = { 318 "NAME": value1, 319 "AGE": value2, 320 "SALARY": value3, 321 "CODES": value4 322}; 323 324if (store != undefined) { 325 (store as relationalStore.RdbStore).createTransaction().then((transaction: relationalStore.Transaction) => { 326 try { 327 let rowId: number = (transaction as relationalStore.Transaction).insertSync("EMPLOYEE", valueBucket1, relationalStore.ConflictResolution.ON_CONFLICT_REPLACE); 328 transaction.commit(); 329 console.info(`Insert is successful, rowId = ${rowId}`); 330 } catch (e) { 331 transaction.rollback(); 332 console.error(`Insert is failed, code is ${e.code},message is ${e.message}`); 333 }; 334 }).catch((err: BusinessError) => { 335 console.error(`createTransaction failed, code is ${err.code},message is ${err.message}`); 336 }); 337} 338``` 339 340## batchInsert<sup>14+</sup> 341 342batchInsert(table: string, values: Array<ValuesBucket>): Promise<number> 343 344Inserts a batch of data into a table. This API uses a promise to return the result. 345 346**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core 347 348**Parameters** 349 350| Name| Type | Mandatory| Description | 351| ------ | ------------------------------------------ | ---- | ---------------------------- | 352| table | string | Yes | Name of the target table. | 353| values | Array<[ValuesBucket](arkts-apis-data-relationalStore-t.md#valuesbucket)> | Yes | An array of data to insert.| 354 355**Return value** 356 357| Type | Description | 358| --------------------- | ----------------------------------------------------------- | 359| Promise<number> | Promise used to return the result. If the operation is successful, the number of inserted data records is returned. Otherwise, **-1** is returned.| 360 361**Error codes** 362 363For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [RDB Store Error Codes](errorcode-data-rdb.md). For details about how to handle error 14800011, see [Database Backup and Restore](../../database/data-backup-and-restore.md). 364 365| **ID**| **Error Message** | 366|-----------| ------------------------------------------------------------ | 367| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. | 368| 14800000 | Inner error. | 369| 14800011 | Failed to open the database because it is corrupted. | 370| 14800014 | The RdbStore or ResultSet is already closed. | 371| 14800021 | SQLite: Generic error. Possible causes: Insert failed or the updated data does not exist. | 372| 14800023 | SQLite: Access permission denied. | 373| 14800024 | SQLite: The database file is locked. | 374| 14800025 | SQLite: A table in the database is locked. | 375| 14800026 | SQLite: The database is out of memory. | 376| 14800027 | SQLite: Attempt to write a readonly database. | 377| 14800028 | SQLite: Some kind of disk I/O error occurred. | 378| 14800029 | SQLite: The database is full. | 379| 14800031 | SQLite: TEXT or BLOB exceeds size limit. | 380| 14800033 | SQLite: Data type mismatch. | 381| 14800047 | The WAL file size exceeds the default limit. | 382 383**Example**: 384 385```ts 386let value1 = "Lisa"; 387let value2 = 18; 388let value3 = 100.5; 389let value4 = new Uint8Array([1, 2, 3, 4, 5]); 390let value5 = "Jack"; 391let value6 = 19; 392let value7 = 101.5; 393let value8 = new Uint8Array([6, 7, 8, 9, 10]); 394let value9 = "Tom"; 395let value10 = 20; 396let value11 = 102.5; 397let value12 = new Uint8Array([11, 12, 13, 14, 15]); 398 399const valueBucket1: relationalStore.ValuesBucket = { 400 'NAME': value1, 401 'AGE': value2, 402 'SALARY': value3, 403 'CODES': value4 404}; 405const valueBucket2: relationalStore.ValuesBucket = { 406 'NAME': value5, 407 'AGE': value6, 408 'SALARY': value7, 409 'CODES': value8 410}; 411const valueBucket3: relationalStore.ValuesBucket = { 412 'NAME': value9, 413 'AGE': value10, 414 'SALARY': value11, 415 'CODES': value12 416}; 417 418let valueBuckets = new Array(valueBucket1, valueBucket2, valueBucket3); 419if (store != undefined) { 420 (store as relationalStore.RdbStore).createTransaction().then((transaction: relationalStore.Transaction) => { 421 transaction.batchInsert("EMPLOYEE", valueBuckets).then((insertNum: number) => { 422 transaction.commit(); 423 console.info(`batchInsert is successful, the number of values that were inserted = ${insertNum}`); 424 }).catch((e: BusinessError) => { 425 transaction.rollback(); 426 console.error(`batchInsert is failed, code is ${e.code},message is ${e.message}`); 427 }); 428 }).catch((err: BusinessError) => { 429 console.error(`createTransaction failed, code is ${err.code},message is ${err.message}`); 430 }); 431} 432``` 433 434## batchInsertSync<sup>14+</sup> 435 436batchInsertSync(table: string, values: Array<ValuesBucket>): number 437 438Inserts a batch of data into a table. This API returns the result synchronously. 439 440**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core 441 442**Parameters** 443 444| Name| Type | Mandatory| Description | 445| ------ | ------------------------------------------ | ---- | ---------------------------- | 446| table | string | Yes | Name of the target table. | 447| values | Array<[ValuesBucket](arkts-apis-data-relationalStore-t.md#valuesbucket)> | Yes | An array of data to insert.| 448 449**Return value** 450 451| Type | Description | 452| ------ | ---------------------------------------------- | 453| number | If the operation is successful, the number of inserted data records is returned. Otherwise, **-1** is returned.| 454 455**Error codes** 456 457For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [RDB Store Error Codes](errorcode-data-rdb.md). For details about how to handle error 14800011, see [Database Backup and Restore](../../database/data-backup-and-restore.md). 458 459| **ID**| **Error Message** | 460| ------------ | ------------------------------------------------------------ | 461| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. | 462| 14800000 | Inner error. | 463| 14800011 | Failed to open the database because it is corrupted. | 464| 14800014 | The RdbStore or ResultSet is already closed. | 465| 14800021 | SQLite: Generic error. Possible causes: Insert failed or the updated data does not exist. | 466| 14800023 | SQLite: Access permission denied. | 467| 14800024 | SQLite: The database file is locked. | 468| 14800025 | SQLite: A table in the database is locked. | 469| 14800026 | SQLite: The database is out of memory. | 470| 14800027 | SQLite: Attempt to write a readonly database. | 471| 14800028 | SQLite: Some kind of disk I/O error occurred. | 472| 14800029 | SQLite: The database is full. | 473| 14800031 | SQLite: TEXT or BLOB exceeds size limit. | 474| 14800033 | SQLite: Data type mismatch. | 475| 14800047 | The WAL file size exceeds the default limit. | 476 477**Example**: 478 479```ts 480let value1 = "Lisa"; 481let value2 = 18; 482let value3 = 100.5; 483let value4 = new Uint8Array([1, 2, 3, 4, 5]); 484let value5 = "Jack"; 485let value6 = 19; 486let value7 = 101.5; 487let value8 = new Uint8Array([6, 7, 8, 9, 10]); 488let value9 = "Tom"; 489let value10 = 20; 490let value11 = 102.5; 491let value12 = new Uint8Array([11, 12, 13, 14, 15]); 492 493const valueBucket1: relationalStore.ValuesBucket = { 494 'NAME': value1, 495 'AGE': value2, 496 'SALARY': value3, 497 'CODES': value4 498}; 499const valueBucket2: relationalStore.ValuesBucket = { 500 'NAME': value5, 501 'AGE': value6, 502 'SALARY': value7, 503 'CODES': value8 504}; 505const valueBucket3: relationalStore.ValuesBucket = { 506 'NAME': value9, 507 'AGE': value10, 508 'SALARY': value11, 509 'CODES': value12 510}; 511 512let valueBuckets = new Array(valueBucket1, valueBucket2, valueBucket3); 513if (store != undefined) { 514 (store as relationalStore.RdbStore).createTransaction().then((transaction: relationalStore.Transaction) => { 515 try { 516 let insertNum: number = (transaction as relationalStore.Transaction).batchInsertSync("EMPLOYEE", valueBuckets); 517 transaction.commit(); 518 console.info(`batchInsert is successful, the number of values that were inserted = ${insertNum}`); 519 } catch (e) { 520 transaction.rollback(); 521 console.error(`batchInsert is failed, code is ${e.code},message is ${e.message}`); 522 }; 523 }).catch((err: BusinessError) => { 524 console.error(`createTransaction failed, code is ${err.code},message is ${err.message}`); 525 }); 526} 527``` 528 529## batchInsertWithConflictResolution<sup>18+</sup> 530 531batchInsertWithConflictResolution(table: string, values: Array<ValuesBucket>, conflict: ConflictResolution): Promise<number> 532 533Inserts a batch of data into a table. This API uses a promise to return the result. 534 535**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core 536 537**Parameters** 538 539| Name| Type | Mandatory| Description | 540| ------ | ------------------------------------------ | ---- | ---------------------------- | 541| table | string | Yes | Name of the target table. | 542| values | Array<[ValuesBucket](arkts-apis-data-relationalStore-t.md#valuesbucket)> | Yes | An array of data to insert.| 543| conflict | [ConflictResolution](arkts-apis-data-relationalStore-e.md#conflictresolution10)| Yes | Resolution used to resolve the conflict. If **ON_CONFLICT_ROLLBACK** is used, the transaction will be rolled back when a conflict occurs.| 544 545**Return value** 546 547| Type | Description | 548| --------------------- | ----------------------------------------------------------- | 549| Promise<number> | Promise used to return the result. If the operation is successful, the number of inserted data records is returned. Otherwise, **-1** is returned.| 550 551**Error codes** 552 553For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [RDB Store Error Codes](errorcode-data-rdb.md). For details about how to handle error 14800011, see [Database Backup and Restore](../../database/data-backup-and-restore.md). 554 555| **ID**| **Error Message** | 556|-----------| ------------------------------------------------------------ | 557| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. | 558| 14800000 | Inner error. | 559| 14800011 | Failed to open the database because it is corrupted. | 560| 14800014 | The RdbStore or ResultSet is already closed. | 561| 14800021 | SQLite: Generic error. Possible causes: Insert failed or the updated data does not exist. | 562| 14800022 | SQLite: Callback routine requested an abort. | 563| 14800023 | SQLite: Access permission denied. | 564| 14800024 | SQLite: The database file is locked. | 565| 14800025 | SQLite: A table in the database is locked. | 566| 14800026 | SQLite: The database is out of memory. | 567| 14800027 | SQLite: Attempt to write a readonly database. | 568| 14800028 | SQLite: Some kind of disk I/O error occurred. | 569| 14800029 | SQLite: The database is full. | 570| 14800031 | SQLite: TEXT or BLOB exceeds size limit. | 571| 14800032 | SQLite: Abort due to constraint violation. | 572| 14800033 | SQLite: Data type mismatch. | 573| 14800034 | SQLite: Library used incorrectly. | 574| 14800047 | The WAL file size exceeds the default limit. | 575 576**Example**: 577 578```ts 579let value1 = "Lisa"; 580let value2 = 18; 581let value3 = 100.5; 582let value4 = new Uint8Array([1, 2, 3, 4, 5]); 583let value5 = "Jack"; 584let value6 = 19; 585let value7 = 101.5; 586let value8 = new Uint8Array([6, 7, 8, 9, 10]); 587let value9 = "Tom"; 588let value10 = 20; 589let value11 = 102.5; 590let value12 = new Uint8Array([11, 12, 13, 14, 15]); 591 592const valueBucket1: relationalStore.ValuesBucket = { 593 'NAME': value1, 594 'AGE': value2, 595 'SALARY': value3, 596 'CODES': value4 597}; 598const valueBucket2: relationalStore.ValuesBucket = { 599 'NAME': value5, 600 'AGE': value6, 601 'SALARY': value7, 602 'CODES': value8 603}; 604const valueBucket3: relationalStore.ValuesBucket = { 605 'NAME': value9, 606 'AGE': value10, 607 'SALARY': value11, 608 'CODES': value12 609}; 610 611let valueBuckets = new Array(valueBucket1, valueBucket2, valueBucket3); 612if (store != undefined) { 613 (store as relationalStore.RdbStore).createTransaction().then((transaction: relationalStore.Transaction) => { 614 transaction.batchInsertWithConflictResolution("EMPLOYEE", valueBuckets, relationalStore.ConflictResolution.ON_CONFLICT_REPLACE).then((insertNum: number) => { 615 transaction.commit(); 616 console.info(`batchInsert is successful, the number of values that were inserted = ${insertNum}`); 617 }).catch((e: BusinessError) => { 618 transaction.rollback(); 619 console.error(`batchInsert is failed, code is ${e.code},message is ${e.message}`); 620 }); 621 }).catch((err: BusinessError) => { 622 console.error(`createTransaction failed, code is ${err.code},message is ${err.message}`); 623 }); 624} 625``` 626 627## batchInsertWithConflictResolutionSync<sup>18+</sup> 628 629batchInsertWithConflictResolutionSync(table: string, values: Array<ValuesBucket>, conflict: ConflictResolution): number 630 631Inserts a batch of data into a table with conflict resolutions. This API returns the result synchronously. 632 633**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core 634 635**Parameters** 636 637| Name| Type | Mandatory| Description | 638| ------ | ------------------------------------------ | ---- | ---------------------------- | 639| table | string | Yes | Name of the target table. | 640| values | Array<[ValuesBucket](arkts-apis-data-relationalStore-t.md#valuesbucket)> | Yes | An array of data to insert.| 641| conflict | [ConflictResolution](arkts-apis-data-relationalStore-e.md#conflictresolution10)| Yes | Resolution used to resolve the conflict. If **ON_CONFLICT_ROLLBACK** is used, the transaction will be rolled back when a conflict occurs.| 642 643**Return value** 644 645| Type | Description | 646| ------ | ---------------------------------------------- | 647| number | If the operation is successful, the number of inserted data records is returned. Otherwise, **-1** is returned.| 648 649**Error codes** 650 651For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [RDB Store Error Codes](errorcode-data-rdb.md). For details about how to handle error 14800011, see [Database Backup and Restore](../../database/data-backup-and-restore.md). 652 653| **ID**| **Error Message** | 654| ------------ | ------------------------------------------------------------ | 655| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. | 656| 14800000 | Inner error. | 657| 14800011 | Failed to open the database because it is corrupted. | 658| 14800014 | The RdbStore or ResultSet is already closed. | 659| 14800021 | SQLite: Generic error. Possible causes: Insert failed or the updated data does not exist. | 660| 14800022 | SQLite: Callback routine requested an abort. | 661| 14800023 | SQLite: Access permission denied. | 662| 14800024 | SQLite: The database file is locked. | 663| 14800025 | SQLite: A table in the database is locked. | 664| 14800026 | SQLite: The database is out of memory. | 665| 14800027 | SQLite: Attempt to write a readonly database. | 666| 14800028 | SQLite: Some kind of disk I/O error occurred. | 667| 14800029 | SQLite: The database is full. | 668| 14800031 | SQLite: TEXT or BLOB exceeds size limit. | 669| 14800032 | SQLite: Abort due to constraint violation. | 670| 14800033 | SQLite: Data type mismatch. | 671| 14800034 | SQLite: Library used incorrectly. | 672| 14800047 | The WAL file size exceeds the default limit. | 673 674**Example**: 675 676```ts 677let value1 = "Lisa"; 678let value2 = 18; 679let value3 = 100.5; 680let value4 = new Uint8Array([1, 2, 3, 4, 5]); 681let value5 = "Jack"; 682let value6 = 19; 683let value7 = 101.5; 684let value8 = new Uint8Array([6, 7, 8, 9, 10]); 685let value9 = "Tom"; 686let value10 = 20; 687let value11 = 102.5; 688let value12 = new Uint8Array([11, 12, 13, 14, 15]); 689 690const valueBucket1: relationalStore.ValuesBucket = { 691 'NAME': value1, 692 'AGE': value2, 693 'SALARY': value3, 694 'CODES': value4 695}; 696const valueBucket2: relationalStore.ValuesBucket = { 697 'NAME': value5, 698 'AGE': value6, 699 'SALARY': value7, 700 'CODES': value8 701}; 702const valueBucket3: relationalStore.ValuesBucket = { 703 'NAME': value9, 704 'AGE': value10, 705 'SALARY': value11, 706 'CODES': value12 707}; 708 709let valueBuckets = new Array(valueBucket1, valueBucket2, valueBucket3); 710if (store != undefined) { 711 (store as relationalStore.RdbStore).createTransaction().then((transaction: relationalStore.Transaction) => { 712 try { 713 let insertNum: number = (transaction as relationalStore.Transaction).batchInsertWithConflictResolutionSync("EMPLOYEE", valueBuckets, relationalStore.ConflictResolution.ON_CONFLICT_REPLACE); 714 transaction.commit(); 715 console.info(`batchInsert is successful, the number of values that were inserted = ${insertNum}`); 716 } catch (e) { 717 transaction.rollback(); 718 console.error(`batchInsert is failed, code is ${e.code},message is ${e.message}`); 719 }; 720 }).catch((err: BusinessError) => { 721 console.error(`createTransaction failed, code is ${err.code},message is ${err.message}`); 722 }); 723} 724``` 725 726## update<sup>14+</sup> 727 728update(values: ValuesBucket, predicates: RdbPredicates, conflict?: ConflictResolution): Promise<number> 729 730Updates data based on the specified **RdbPredicates** object. This API uses a promise to return the result. Due to the limit of the shared memory (max. 2 MB), a single data record cannot exceed 2 MB. Otherwise, the query operation will fail. 731 732**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core 733 734**Parameters** 735 736| Name | Type | Mandatory| Description | 737| ---------- | ------------------------------------------- | ---- | ------------------------------------------------------------ | 738| values | [ValuesBucket](arkts-apis-data-relationalStore-t.md#valuesbucket) | Yes | Rows of data to update in the RDB store. The key-value pair is associated with the column name in the target table.| 739| predicates | [RdbPredicates](arkts-apis-data-relationalStore-RdbPredicates.md) | Yes | Update conditions specified by the **RdbPredicates** object. | 740| conflict | [ConflictResolution](arkts-apis-data-relationalStore-e.md#conflictresolution10)| No | Resolution used to resolve the conflict. <br>Default value: **relationalStore.ConflictResolution.ON_CONFLICT_NONE**. | 741 742**Return value** 743 744| Type | Description | 745| --------------------- | ----------------------------------------- | 746| Promise<number> | Promise used to return the number of rows updated.| 747 748**Error codes** 749 750For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [RDB Store Error Codes](errorcode-data-rdb.md). For details about how to handle error 14800011, see [Database Backup and Restore](../../database/data-backup-and-restore.md). 751 752| **ID**| **Error Message** | 753|-----------| ------------------------------------------------------------ | 754| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. | 755| 14800000 | Inner error. | 756| 14800011 | Failed to open the database because it is corrupted. | 757| 14800014 | The RdbStore or ResultSet is already closed. | 758| 14800021 | SQLite: Generic error. Possible causes: Insert failed or the updated data does not exist. | 759| 14800023 | SQLite: Access permission denied. | 760| 14800024 | SQLite: The database file is locked. | 761| 14800025 | SQLite: A table in the database is locked. | 762| 14800026 | SQLite: The database is out of memory. | 763| 14800027 | SQLite: Attempt to write a readonly database. | 764| 14800028 | SQLite: Some kind of disk I/O error occurred. | 765| 14800029 | SQLite: The database is full. | 766| 14800031 | SQLite: TEXT or BLOB exceeds size limit. | 767| 14800033 | SQLite: Data type mismatch. | 768| 14800047 | The WAL file size exceeds the default limit. | 769 770**Example**: 771 772```ts 773let value1 = "Rose"; 774let value2 = 22; 775let value3 = 200.5; 776let value4 = new Uint8Array([1, 2, 3, 4, 5]); 777 778// You can use either of the following: 779const valueBucket1: relationalStore.ValuesBucket = { 780 'NAME': value1, 781 'AGE': value2, 782 'SALARY': value3, 783 'CODES': value4 784}; 785const valueBucket2: relationalStore.ValuesBucket = { 786 NAME: value1, 787 AGE: value2, 788 SALARY: value3, 789 CODES: value4 790}; 791const valueBucket3: relationalStore.ValuesBucket = { 792 "NAME": value1, 793 "AGE": value2, 794 "SALARY": value3, 795 "CODES": value4 796}; 797 798let predicates = new relationalStore.RdbPredicates('EMPLOYEE'); 799predicates.equalTo("NAME", "Lisa"); 800 801if (store != undefined) { 802 (store as relationalStore.RdbStore).createTransaction().then((transaction: relationalStore.Transaction) => { 803 transaction.update(valueBucket1, predicates, relationalStore.ConflictResolution.ON_CONFLICT_REPLACE).then(async (rows: Number) => { 804 transaction.commit(); 805 console.info(`Updated row count: ${rows}`); 806 }).catch((e: BusinessError) => { 807 transaction.rollback(); 808 console.error(`Updated failed, code is ${e.code},message is ${e.message}`); 809 }); 810 }).catch((err: BusinessError) => { 811 console.error(`createTransaction failed, code is ${err.code},message is ${err.message}`); 812 }); 813} 814``` 815 816## updateSync<sup>14+</sup> 817 818updateSync(values: ValuesBucket, predicates: RdbPredicates, conflict?: ConflictResolution): number 819 820Updates data in the RDB store based on the specified **RdbPredicates** object. This API returns the result synchronously. Due to the limit of the shared memory (max. 2 MB), a single data record cannot exceed 2 MB. Otherwise, the query operation will fail. 821 822**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core 823 824**Parameters** 825 826| Name | Type | Mandatory| Description | 827| ---------- | ------------------------------------------- | ---- | ------------------------------------------------------------ | 828| values | [ValuesBucket](arkts-apis-data-relationalStore-t.md#valuesbucket) | Yes | Rows of data to update in the RDB store. The key-value pair is associated with the column name in the target table.| 829| predicates | [RdbPredicates](arkts-apis-data-relationalStore-RdbPredicates.md) | Yes | Update conditions specified by the **RdbPredicates** object. | 830| conflict | [ConflictResolution](arkts-apis-data-relationalStore-e.md#conflictresolution10)| No | Resolution used to resolve the conflict. <br>Default value: **relationalStore.ConflictResolution.ON_CONFLICT_NONE**.| 831 832**Return value** 833 834| Type | Description | 835| ------ | ------------------ | 836| number | Number of rows updated.| 837 838**Error codes** 839 840For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [RDB Store Error Codes](errorcode-data-rdb.md). For details about how to handle error 14800011, see [Database Backup and Restore](../../database/data-backup-and-restore.md). 841 842| **ID**| **Error Message** | 843| ------------ | ------------------------------------------------------------ | 844| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. | 845| 14800000 | Inner error. | 846| 14800011 | Failed to open the database because it is corrupted. | 847| 14800014 | The RdbStore or ResultSet is already closed. | 848| 14800021 | SQLite: Generic error. Possible causes: Insert failed or the updated data does not exist. | 849| 14800023 | SQLite: Access permission denied. | 850| 14800024 | SQLite: The database file is locked. | 851| 14800025 | SQLite: A table in the database is locked. | 852| 14800026 | SQLite: The database is out of memory. | 853| 14800027 | SQLite: Attempt to write a readonly database. | 854| 14800028 | SQLite: Some kind of disk I/O error occurred. | 855| 14800029 | SQLite: The database is full. | 856| 14800031 | SQLite: TEXT or BLOB exceeds size limit. | 857| 14800033 | SQLite: Data type mismatch. | 858| 14800047 | The WAL file size exceeds the default limit. | 859 860**Example**: 861 862```ts 863let value1 = "Rose"; 864let value2 = 22; 865let value3 = 200.5; 866let value4 = new Uint8Array([1, 2, 3, 4, 5]); 867 868// You can use either of the following: 869const valueBucket1: relationalStore.ValuesBucket = { 870 'NAME': value1, 871 'AGE': value2, 872 'SALARY': value3, 873 'CODES': value4 874}; 875const valueBucket2: relationalStore.ValuesBucket = { 876 NAME: value1, 877 AGE: value2, 878 SALARY: value3, 879 CODES: value4 880}; 881const valueBucket3: relationalStore.ValuesBucket = { 882 "NAME": value1, 883 "AGE": value2, 884 "SALARY": value3, 885 "CODES": value4 886}; 887 888let predicates = new relationalStore.RdbPredicates("EMPLOYEE"); 889predicates.equalTo("NAME", "Lisa"); 890 891if (store != undefined) { 892 (store as relationalStore.RdbStore).createTransaction().then((transaction: relationalStore.Transaction) => { 893 try { 894 let rows: Number = (transaction as relationalStore.Transaction).updateSync(valueBucket1, predicates, relationalStore.ConflictResolution.ON_CONFLICT_REPLACE); 895 transaction.commit(); 896 console.info(`Updated row count: ${rows}`); 897 } catch (e) { 898 transaction.rollback(); 899 console.error(`Updated failed, code is ${e.code},message is ${e.message}`); 900 }; 901 }).catch((err: BusinessError) => { 902 console.error(`createTransaction failed, code is ${err.code},message is ${err.message}`); 903 }); 904} 905``` 906 907## delete<sup>14+</sup> 908 909delete(predicates: RdbPredicates):Promise<number> 910 911Deletes data from the RDB store based on the specified **RdbPredicates** object. This API uses a promise to return the result. 912 913**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core 914 915**Parameters** 916 917| Name | Type | Mandatory| Description | 918| ---------- | ------------------------------------ | ---- | ----------------------------------------- | 919| predicates | [RdbPredicates](arkts-apis-data-relationalStore-RdbPredicates.md) | Yes | Deletion conditions specified by the **RdbPredicates** object.| 920 921**Return value** 922 923| Type | Description | 924| --------------------- | ------------------------------- | 925| Promise<number> | Promise used to return the number of rows deleted.| 926 927**Error codes** 928 929For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [RDB Store Error Codes](errorcode-data-rdb.md). For details about how to handle error 14800011, see [Database Backup and Restore](../../database/data-backup-and-restore.md). 930 931| **ID**| **Error Message** | 932|-----------| ------------------------------------------------------------ | 933| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. | 934| 14800000 | Inner error. | 935| 14800011 | Failed to open the database because it is corrupted. | 936| 14800014 | The RdbStore or ResultSet is already closed. | 937| 14800021 | SQLite: Generic error. Possible causes: Insert failed or the updated data does not exist. | 938| 14800023 | SQLite: Access permission denied. | 939| 14800024 | SQLite: The database file is locked. | 940| 14800025 | SQLite: A table in the database is locked. | 941| 14800026 | SQLite: The database is out of memory. | 942| 14800027 | SQLite: Attempt to write a readonly database. | 943| 14800028 | SQLite: Some kind of disk I/O error occurred. | 944| 14800029 | SQLite: The database is full. | 945| 14800031 | SQLite: TEXT or BLOB exceeds size limit. | 946| 14800033 | SQLite: Data type mismatch. | 947| 14800047 | The WAL file size exceeds the default limit. | 948 949**Example**: 950 951```ts 952let predicates = new relationalStore.RdbPredicates("EMPLOYEE"); 953predicates.equalTo("NAME", "Lisa"); 954 955if (store != undefined) { 956 (store as relationalStore.RdbStore).createTransaction().then((transaction: relationalStore.Transaction) => { 957 transaction.delete(predicates).then((rows: Number) => { 958 transaction.commit(); 959 console.info(`Delete rows: ${rows}`); 960 }).catch((e: BusinessError) => { 961 transaction.rollback(); 962 console.error(`Delete failed, code is ${e.code},message is ${e.message}`); 963 }); 964 }).catch((err: BusinessError) => { 965 console.error(`createTransaction failed, code is ${err.code},message is ${err.message}`); 966 }); 967} 968``` 969 970## deleteSync<sup>14+</sup> 971 972deleteSync(predicates: RdbPredicates): number 973 974Deletes data from the RDB store based on the specified **RdbPredicates** object. This API returns the result synchronously. 975 976**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core 977 978**Parameters** 979 980| Name | Type | Mandatory| Description | 981| ---------- | ------------------------------- | ---- | --------------------------------------- | 982| predicates | [RdbPredicates](arkts-apis-data-relationalStore-RdbPredicates.md) | Yes | Deletion conditions specified by the **RdbPredicates** object.| 983 984**Return value** 985 986| Type | Description | 987| ------ | ------------------ | 988| number | Number of rows deleted.| 989 990**Error codes** 991 992For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [RDB Store Error Codes](errorcode-data-rdb.md). For details about how to handle error 14800011, see [Database Backup and Restore](../../database/data-backup-and-restore.md). 993 994| **ID**| **Error Message** | 995| ------------ | ------------------------------------------------------------ | 996| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. | 997| 14800000 | Inner error. | 998| 14800011 | Failed to open the database because it is corrupted. | 999| 14800014 | The RdbStore or ResultSet is already closed. | 1000| 14800021 | SQLite: Generic error. Possible causes: Insert failed or the updated data does not exist. | 1001| 14800023 | SQLite: Access permission denied. | 1002| 14800024 | SQLite: The database file is locked. | 1003| 14800025 | SQLite: A table in the database is locked. | 1004| 14800026 | SQLite: The database is out of memory. | 1005| 14800027 | SQLite: Attempt to write a readonly database. | 1006| 14800028 | SQLite: Some kind of disk I/O error occurred. | 1007| 14800029 | SQLite: The database is full. | 1008| 14800031 | SQLite: TEXT or BLOB exceeds size limit. | 1009| 14800033 | SQLite: Data type mismatch. | 1010| 14800047 | The WAL file size exceeds the default limit. | 1011 1012**Example**: 1013 1014```ts 1015let predicates = new relationalStore.RdbPredicates("EMPLOYEE"); 1016predicates.equalTo("NAME", "Lisa"); 1017 1018if (store != undefined) { 1019 (store as relationalStore.RdbStore).createTransaction().then((transaction: relationalStore.Transaction) => { 1020 try { 1021 let rows: Number = (transaction as relationalStore.Transaction).deleteSync(predicates); 1022 transaction.commit(); 1023 console.info(`Delete rows: ${rows}`); 1024 } catch (e) { 1025 transaction.rollback(); 1026 console.error(`Delete failed, code is ${e.code},message is ${e.message}`); 1027 }; 1028 }).catch((err: BusinessError) => { 1029 console.error(`createTransaction failed, code is ${err.code},message is ${err.message}`); 1030 }); 1031} 1032``` 1033 1034## query<sup>14+</sup> 1035 1036query(predicates: RdbPredicates, columns?: Array<string>): Promise<ResultSet> 1037 1038Queries data from the RDB store based on specified conditions. This API uses a promise to return the result. Due to the limit of the shared memory (max. 2 MB), a single data record cannot exceed 2 MB. Otherwise, the query operation will fail. 1039 1040**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core 1041 1042**Parameters** 1043 1044| Name | Type | Mandatory| Description | 1045| ---------- | ------------------------------------ | ---- | ------------------------------------------------ | 1046| predicates | [RdbPredicates](arkts-apis-data-relationalStore-RdbPredicates.md) | Yes | Query conditions specified by the **RdbPredicates** object. | 1047| columns | Array<string> | No | Columns to query. If this parameter is not specified, the query applies to all columns.| 1048 1049**Return value** 1050 1051| Type | Description | 1052| ------------------------------------------------------- | -------------------------------------------------- | 1053| Promise<[ResultSet](arkts-apis-data-relationalStore-ResultSet.md)> | Promise used to return the result. If the operation is successful, a **ResultSet** object will be returned.| 1054 1055**Error codes** 1056 1057For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [RDB Store Error Codes](errorcode-data-rdb.md). 1058 1059| **ID**| **Error Message** | 1060|-----------| ------------------------------------------------------------ | 1061| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. | 1062| 14800000 | Inner error. | 1063| 14800011 | Failed to open the database because it is corrupted. | 1064| 14800014 | The RdbStore or ResultSet is already closed. | 1065| 14800021 | SQLite: Generic error. Possible causes: Insert failed or the updated data does not exist. | 1066| 14800023 | SQLite: Access permission denied. | 1067| 14800024 | SQLite: The database file is locked. | 1068| 14800026 | SQLite: The database is out of memory. | 1069| 14800028 | SQLite: Some kind of disk I/O error occurred. | 1070| 14800047 | The WAL file size exceeds the default limit. | 1071 1072 1073**Example**: 1074 1075```ts 1076let predicates = new relationalStore.RdbPredicates("EMPLOYEE"); 1077predicates.equalTo("NAME", "Rose"); 1078 1079if (store != undefined) { 1080 (store as relationalStore.RdbStore).createTransaction().then((transaction: relationalStore.Transaction) => { 1081 transaction.query(predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"]).then(async (resultSet: relationalStore.ResultSet) => { 1082 console.info(`ResultSet column names: ${resultSet.columnNames}, column count: ${resultSet.columnCount}`); 1083 // resultSet is a cursor of a data set. By default, the cursor points to the -1st record. Valid data starts from 0. 1084 while (resultSet.goToNextRow()) { 1085 const id = resultSet.getLong(resultSet.getColumnIndex("ID")); 1086 const name = resultSet.getString(resultSet.getColumnIndex("NAME")); 1087 const age = resultSet.getLong(resultSet.getColumnIndex("AGE")); 1088 const salary = resultSet.getDouble(resultSet.getColumnIndex("SALARY")); 1089 console.info(`id=${id}, name=${name}, age=${age}, salary=${salary}`); 1090 } 1091 // Release the memory of resultSet. If the memory is not released, FD or memory leaks may occur. 1092 resultSet.close(); 1093 transaction.commit(); 1094 }).catch((e: BusinessError) => { 1095 transaction.rollback(); 1096 console.error(`Query failed, code is ${e.code},message is ${e.message}`); 1097 }); 1098 }).catch((err: BusinessError) => { 1099 console.error(`createTransaction failed, code is ${err.code},message is ${err.message}`); 1100 }); 1101} 1102``` 1103 1104## querySync<sup>14+</sup> 1105 1106querySync(predicates: RdbPredicates, columns?: Array<string>): ResultSet 1107 1108Queries data in a database based on specified conditions. This API returns the result synchronously. If complex logic and a large number of loops are involved in the operations on the **resultSet** obtained by **querySync**, the freeze problem may occur. You are advised to perform this operation in the [taskpool](../apis-arkts/js-apis-taskpool.md) thread. 1109 1110**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core 1111 1112**Parameters** 1113 1114| Name | Type | Mandatory| Description | 1115| ---------- | ------------------------------- | ---- | ------------------------------------------------------------ | 1116| predicates | [RdbPredicates](arkts-apis-data-relationalStore-RdbPredicates.md) | Yes | Query conditions specified by the **RdbPredicates** object. | 1117| columns | Array<string> | No | Columns to query. If this parameter is not specified, the query applies to all columns. The default value is null.| 1118 1119**Return value** 1120 1121| Type | Description | 1122| ----------------------- | ----------------------------------- | 1123| [ResultSet](arkts-apis-data-relationalStore-ResultSet.md) | If the operation is successful, a **ResultSet** object will be returned.| 1124 1125**Error codes** 1126 1127For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [RDB Store Error Codes](errorcode-data-rdb.md). 1128 1129| **ID**| **Error Message** | 1130| ------------ | ------------------------------------------------------------ | 1131| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. | 1132| 14800000 | Inner error. | 1133| 14800011 | Failed to open the database because it is corrupted. | 1134| 14800014 | The RdbStore or ResultSet is already closed. | 1135| 14800021 | SQLite: Generic error. Possible causes: Insert failed or the updated data does not exist. | 1136| 14800023 | SQLite: Access permission denied. | 1137| 14800024 | SQLite: The database file is locked. | 1138| 14800025 | SQLite: A table in the database is locked. | 1139| 14800026 | SQLite: The database is out of memory. | 1140| 14800028 | SQLite: Some kind of disk I/O error occurred. | 1141| 14800047 | The WAL file size exceeds the default limit. | 1142 1143**Example**: 1144 1145```ts 1146let predicates = new relationalStore.RdbPredicates("EMPLOYEE"); 1147predicates.equalTo("NAME", "Rose"); 1148 1149if (store != undefined) { 1150 (store as relationalStore.RdbStore).createTransaction().then(async (transaction: relationalStore.Transaction) => { 1151 try { 1152 let resultSet: relationalStore.ResultSet = (transaction as relationalStore.Transaction).querySync(predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"]); 1153 console.info(`ResultSet column names: ${resultSet.columnNames}, column count: ${resultSet.columnCount}`); 1154 // resultSet is a cursor of a data set. By default, the cursor points to the -1st record. Valid data starts from 0. 1155 while (resultSet.goToNextRow()) { 1156 const id = resultSet.getLong(resultSet.getColumnIndex("ID")); 1157 const name = resultSet.getString(resultSet.getColumnIndex("NAME")); 1158 const age = resultSet.getLong(resultSet.getColumnIndex("AGE")); 1159 const salary = resultSet.getDouble(resultSet.getColumnIndex("SALARY")); 1160 console.info(`id=${id}, name=${name}, age=${age}, salary=${salary}`); 1161 } 1162 // Release the memory of resultSet. If the memory is not released, FD or memory leaks may occur. 1163 resultSet.close(); 1164 transaction.commit(); 1165 } catch (e) { 1166 transaction.rollback(); 1167 console.error(`Query failed, code is ${e.code},message is ${e.message}`); 1168 }; 1169 }).catch((err: BusinessError) => { 1170 console.error(`createTransaction failed, code is ${err.code},message is ${err.message}`); 1171 }); 1172} 1173``` 1174 1175## querySql<sup>14+</sup> 1176 1177querySql(sql: string, args?: Array<ValueType>): Promise<ResultSet> 1178 1179Queries data in the RDB store using the specified SQL statement. The number of relational operators between expressions and operators in the SQL statement cannot exceed 1000. This API uses a promise to return the result. 1180 1181**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core 1182 1183**Parameters** 1184 1185| Name | Type | Mandatory| Description | 1186| -------- | ------------------------------------ | ---- | ------------------------------------------------------------ | 1187| sql | string | Yes | SQL statement to run. | 1188| args | Array<[ValueType](arkts-apis-data-relationalStore-t.md#valuetype)> | No | Arguments in the SQL statement. The value corresponds to the placeholders in the SQL parameter statement. If the SQL parameter statement is complete, leave this parameter blank.| 1189 1190**Return value** 1191 1192| Type | Description | 1193| ------------------------------------------------------- | -------------------------------------------------- | 1194| Promise<[ResultSet](arkts-apis-data-relationalStore-ResultSet.md)> | Promise used to return the result. If the operation is successful, a **ResultSet** object will be returned.| 1195 1196**Error codes** 1197 1198For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [RDB Store Error Codes](errorcode-data-rdb.md). 1199 1200| **ID**| **Error Message** | 1201|-----------| ------------------------------------------------------------ | 1202| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. | 1203| 14800000 | Inner error. | 1204| 14800011 | Failed to open the database because it is corrupted. | 1205| 14800014 | The RdbStore or ResultSet is already closed. | 1206| 14800021 | SQLite: Generic error. Possible causes: Insert failed or the updated data does not exist. | 1207| 14800023 | SQLite: Access permission denied. | 1208| 14800024 | SQLite: The database file is locked. | 1209| 14800025 | SQLite: A table in the database is locked. | 1210| 14800026 | SQLite: The database is out of memory. | 1211| 14800028 | SQLite: Some kind of disk I/O error occurred. | 1212| 14800047 | The WAL file size exceeds the default limit. | 1213 1214**Example**: 1215 1216```ts 1217if (store != undefined) { 1218 (store as relationalStore.RdbStore).createTransaction().then((transaction: relationalStore.Transaction) => { 1219 transaction.querySql("SELECT * FROM EMPLOYEE CROSS JOIN BOOK WHERE BOOK.NAME = 'sanguo'").then(async (resultSet: relationalStore.ResultSet) => { 1220 console.info(`ResultSet column names: ${resultSet.columnNames}, column count: ${resultSet.columnCount}`); 1221 // resultSet is a cursor of a data set. By default, the cursor points to the -1st record. Valid data starts from 0. 1222 while (resultSet.goToNextRow()) { 1223 const id = resultSet.getLong(resultSet.getColumnIndex("ID")); 1224 const name = resultSet.getString(resultSet.getColumnIndex("NAME")); 1225 const age = resultSet.getLong(resultSet.getColumnIndex("AGE")); 1226 const salary = resultSet.getDouble(resultSet.getColumnIndex("SALARY")); 1227 console.info(`id=${id}, name=${name}, age=${age}, salary=${salary}`); 1228 } 1229 // Release the memory of resultSet. If the memory is not released, FD or memory leaks may occur. 1230 resultSet.close(); 1231 transaction.commit(); 1232 }).catch((e: BusinessError) => { 1233 transaction.rollback(); 1234 console.error(`Query failed, code is ${e.code},message is ${e.message}`); 1235 }); 1236 }).catch((err: BusinessError) => { 1237 console.error(`createTransaction failed, code is ${err.code},message is ${err.message}`); 1238 }); 1239} 1240``` 1241 1242## querySqlSync<sup>14+</sup> 1243 1244querySqlSync(sql: string, args?: Array<ValueType>): ResultSet 1245 1246Queries data in the RDB store using the specified SQL statement. The number of relational operators between expressions and operators in the SQL statement cannot exceed 1000. If complex logic and a large number of loops are involved in the operations on the **resultSet** obtained by **querySqlSync**, the freeze problem may occur. You are advised to perform this operation in the [taskpool](../apis-arkts/js-apis-taskpool.md) thread. 1247 1248**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core 1249 1250**Parameters** 1251 1252| Name | Type | Mandatory| Description | 1253| -------- | ------------------------------------ | ---- | ------------------------------------------------------------ | 1254| sql | string | Yes | SQL statement to run. | 1255| args | Array<[ValueType](arkts-apis-data-relationalStore-t.md#valuetype)> | No | Arguments in the SQL statement. The value corresponds to the placeholders in the SQL parameter statement. If the SQL parameter statement is complete, leave this parameter blank. The default value is null.| 1256 1257**Return value** 1258 1259| Type | Description | 1260| ----------------------- | ----------------------------------- | 1261| [ResultSet](arkts-apis-data-relationalStore-ResultSet.md) | If the operation is successful, a **ResultSet** object will be returned.| 1262 1263**Error codes** 1264 1265For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [RDB Store Error Codes](errorcode-data-rdb.md). 1266 1267| **ID**| **Error Message** | 1268| ------------ | ------------------------------------------------------------ | 1269| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. | 1270| 14800000 | Inner error. | 1271| 14800011 | Failed to open the database because it is corrupted. | 1272| 14800014 | The RdbStore or ResultSet is already closed. | 1273| 14800021 | SQLite: Generic error. Possible causes: Insert failed or the updated data does not exist. | 1274| 14800023 | SQLite: Access permission denied. | 1275| 14800024 | SQLite: The database file is locked. | 1276| 14800025 | SQLite: A table in the database is locked. | 1277| 14800026 | SQLite: The database is out of memory. | 1278| 14800028 | SQLite: Some kind of disk I/O error occurred. | 1279| 14800047 | The WAL file size exceeds the default limit. | 1280 1281**Example**: 1282 1283```ts 1284if (store != undefined) { 1285 (store as relationalStore.RdbStore).createTransaction().then(async (transaction: relationalStore.Transaction) => { 1286 try { 1287 let resultSet: relationalStore.ResultSet = (transaction as relationalStore.Transaction).querySqlSync("SELECT * FROM EMPLOYEE CROSS JOIN BOOK WHERE BOOK.NAME = 'sanguo'"); 1288 console.info(`ResultSet column names: ${resultSet.columnNames}, column count: ${resultSet.columnCount}`); 1289 // resultSet is a cursor of a data set. By default, the cursor points to the -1st record. Valid data starts from 0. 1290 while (resultSet.goToNextRow()) { 1291 const id = resultSet.getLong(resultSet.getColumnIndex("ID")); 1292 const name = resultSet.getString(resultSet.getColumnIndex("NAME")); 1293 const age = resultSet.getLong(resultSet.getColumnIndex("AGE")); 1294 const salary = resultSet.getDouble(resultSet.getColumnIndex("SALARY")); 1295 console.info(`id=${id}, name=${name}, age=${age}, salary=${salary}`); 1296 } 1297 // Release the memory of resultSet. If the memory is not released, FD or memory leaks may occur. 1298 resultSet.close(); 1299 transaction.commit(); 1300 } catch (e) { 1301 transaction.rollback(); 1302 console.error(`Query failed, code is ${e.code},message is ${e.message}`); 1303 }; 1304 }).catch((err: BusinessError) => { 1305 console.error(`createTransaction failed, code is ${err.code},message is ${err.message}`); 1306 }); 1307} 1308``` 1309 1310## execute<sup>14+</sup> 1311 1312execute(sql: string, args?: Array<ValueType>): Promise<ValueType> 1313 1314Executes an SQL statement that contains specified arguments. The number of relational operators between expressions and operators in the statement cannot exceed 1000. This API uses a promise to return a value of the ValueType type. 1315 1316This API can be used to add, delete, and modify data, run SQL statements of the PRAGMA syntax, and create, delete, and modify a table. The type of the return value varies, depending on the execution result. 1317 1318This API does not support query, database attachment, and transaction operations. You can use [querySql](#querysql14) or [query](#query14) to query data, and use [attach](arkts-apis-data-relationalStore-RdbStore.md#attach12) to attach a database. 1319 1320Statements separated by semicolons (\;) are not supported. 1321 1322**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core 1323 1324**Parameters** 1325 1326| Name | Type | Mandatory| Description | 1327| -------- | ------------------------------------ | ---- | ------------------------------------------------------------ | 1328| sql | string | Yes | SQL statement to run. | 1329| args | Array<[ValueType](arkts-apis-data-relationalStore-t.md#valuetype)> | No | Arguments in the SQL statement. The value corresponds to the placeholders in the SQL parameter statement. If the SQL parameter statement is complete, leave this parameter blank.| 1330 1331**Return value** 1332 1333| Type | Description | 1334| ------------------- | ------------------------- | 1335| Promise<[ValueType](arkts-apis-data-relationalStore-t.md#valuetype)> | Promise used to return the SQL execution result.| 1336 1337**Error codes** 1338 1339For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [RDB Store Error Codes](errorcode-data-rdb.md). For details about how to handle error 14800011, see [Database Backup and Restore](../../database/data-backup-and-restore.md). 1340 1341| **ID**| **Error Message** | 1342|-----------| ------------------------------------------------------------ | 1343| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. | 1344| 801 | Capability not supported the sql(attach,begin,commit,rollback etc.). | 1345| 14800000 | Inner error. | 1346| 14800011 | Failed to open the database because it is corrupted. | 1347| 14800014 | The RdbStore or ResultSet is already closed. | 1348| 14800021 | SQLite: Generic error. Possible causes: Insert failed or the updated data does not exist. | 1349| 14800023 | SQLite: Access permission denied. | 1350| 14800024 | SQLite: The database file is locked. | 1351| 14800025 | SQLite: A table in the database is locked. | 1352| 14800026 | SQLite: The database is out of memory. | 1353| 14800027 | SQLite: Attempt to write a readonly database. | 1354| 14800028 | SQLite: Some kind of disk I/O error occurred. | 1355| 14800029 | SQLite: The database is full. | 1356| 14800031 | SQLite: TEXT or BLOB exceeds size limit. | 1357| 14800033 | SQLite: Data type mismatch. | 1358| 14800047 | The WAL file size exceeds the default limit. | 1359 1360**Example**: 1361 1362```ts 1363// Delete all data from the table. 1364if (store != undefined) { 1365 const SQL_DELETE_TABLE = 'DELETE FROM test'; 1366 (store as relationalStore.RdbStore).createTransaction().then((transaction: relationalStore.Transaction) => { 1367 transaction.execute(SQL_DELETE_TABLE).then((data) => { 1368 transaction.commit(); 1369 console.info(`delete result: ${data}`); 1370 }).catch((e: BusinessError) => { 1371 transaction.rollback(); 1372 console.error(`delete failed, code is ${e.code}, message is ${e.message}`); 1373 }); 1374 }).catch((err: BusinessError) => { 1375 console.error(`createTransaction failed, code is ${err.code},message is ${err.message}`); 1376 }); 1377} 1378``` 1379 1380## executeSync<sup>14+</sup> 1381 1382executeSync(sql: string, args?: Array<ValueType>): ValueType 1383 1384Executes an SQL statement that contains specified arguments. The number of relational operators between expressions and operators in the statement cannot exceed 1000. This API returns a value of theValueType type. 1385 1386This API can be used to add, delete, and modify data, run SQL statements of the PRAGMA syntax, and create, delete, and modify a table. The type of the return value varies, depending on the execution result. 1387 1388This API does not support query, database attachment, and transaction operations. You can use [querySql](#querysql14) or [query](#query14) to query data, and use [attach](arkts-apis-data-relationalStore-RdbStore.md#attach12) to attach a database. 1389 1390Statements separated by semicolons (\;) are not supported. 1391 1392**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core 1393 1394**Parameters** 1395 1396| Name| Type | Mandatory| Description | 1397| ------ | ------------------------------------ | ---- | ------------------------------------------------------------ | 1398| sql | string | Yes | SQL statement to run. | 1399| args | Array<[ValueType](arkts-apis-data-relationalStore-t.md#valuetype)> | No | Arguments in the SQL statement. The value corresponds to the placeholders in the SQL parameter statement. If this parameter is left blank or set to **null** or **undefined**, the SQL statement is complete. The default value is null.| 1400 1401**Return value** 1402 1403| Type | Description | 1404| ----------------------- | ------------------- | 1405| [ValueType](arkts-apis-data-relationalStore-t.md#valuetype) | SQL execution result.| 1406 1407**Error codes** 1408 1409For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [RDB Store Error Codes](errorcode-data-rdb.md). For details about how to handle error 14800011, see [Database Backup and Restore](../../database/data-backup-and-restore.md). 1410 1411| **ID**| **Error Message** | 1412| ------------ | ------------------------------------------------------------ | 1413| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. | 1414| 801 | Capability not supported the sql(attach,begin,commit,rollback etc.). | 1415| 14800000 | Inner error. | 1416| 14800011 | Failed to open the database because it is corrupted. | 1417| 14800014 | The RdbStore or ResultSet is already closed. | 1418| 14800021 | SQLite: Generic error. Possible causes: Insert failed or the updated data does not exist. | 1419| 14800023 | SQLite: Access permission denied. | 1420| 14800024 | SQLite: The database file is locked. | 1421| 14800025 | SQLite: A table in the database is locked. | 1422| 14800026 | SQLite: The database is out of memory. | 1423| 14800027 | SQLite: Attempt to write a readonly database. | 1424| 14800028 | SQLite: Some kind of disk I/O error occurred. | 1425| 14800029 | SQLite: The database is full. | 1426| 14800031 | SQLite: TEXT or BLOB exceeds size limit. | 1427| 14800033 | SQLite: Data type mismatch. | 1428| 14800047 | The WAL file size exceeds the default limit. | 1429 1430**Example**: 1431 1432```ts 1433// Delete all data from the table. 1434if (store != undefined) { 1435 (store as relationalStore.RdbStore).createTransaction().then((transaction: relationalStore.Transaction) => { 1436 const SQL_DELETE_TABLE = 'DELETE FROM test'; 1437 try { 1438 let data = (transaction as relationalStore.Transaction).executeSync(SQL_DELETE_TABLE); 1439 transaction.commit(); 1440 console.info(`delete result: ${data}`); 1441 } catch (e) { 1442 transaction.rollback(); 1443 console.error(`delete failed, code is ${e.code}, message is ${e.message}`); 1444 }; 1445 }).catch((err: BusinessError) => { 1446 console.error(`createTransaction failed, code is ${err.code},message is ${err.message}`); 1447 }); 1448} 1449``` 1450