sqliteHow do I use SQLite transactions?
SQLite transactions are used to ensure data integrity. Transactions are a set of operations that either all succeed or all fail.
To use SQLite transactions, begin a transaction using the BEGIN TRANSACTION
statement. All subsequent SQL statements will be part of the transaction. When all statements have been executed, use the COMMIT
statement to save the changes or ROLLBACK
to undo them.
Example code
BEGIN TRANSACTION;
UPDATE accounts SET balance = balance - 100 WHERE id = 1;
UPDATE accounts SET balance = balance + 100 WHERE id = 2;
COMMIT;
The code above will transfer 100 units from account 1 to account 2. If either of the UPDATE
statements fail, the ROLLBACK
statement will undo any changes made.
The code can be broken down as follows:
BEGIN TRANSACTION;
- Starts the transactionUPDATE accounts SET balance = balance - 100 WHERE id = 1;
- Subtracts 100 units from account 1UPDATE accounts SET balance = balance + 100 WHERE id = 2;
- Adds 100 units to account 2COMMIT;
- Commits the changes and saves them
For more information, see the SQLite documentation.
More of Sqlite
- How can SQLite and ZFS be used together for software development?
- How do I use the SQLite ZIP VFS to compress a database?
- How do I show the databases in SQLite?
- How do I format an SQLite database with version 3?
- How can I use SQLite with Zabbix?
- How do I format a date in SQLite using the YYYYMMDD format?
- How do I use SQLite to retrieve data from a specific year?
- How can I use Python to update a SQLite database?
- How can I use an upsert statement to update data in a SQLite database?
- How do I call sqlitepcl.raw.setprovider() when using SQLite?
See more codes...