Junior — Middle
What are the main commands used for transaction control in a relational database?
sobes.tech AI
Answer from AI
The following are the main SQL commands used to control transactions in relational databases:
BEGINorSTART TRANSACTION— starts a new transaction.COMMIT— saves all changes made within the transaction.ROLLBACK— reverts all changes made since the transaction started.
Example of usage in Python with the sqlite3 library:
import sqlite3
conn = sqlite3.connect('example.db')
cursor = conn.cursor()
try:
conn.execute('BEGIN')
cursor.execute("INSERT INTO users(name) VALUES ('Alice')")
cursor.execute("INSERT INTO users(name) VALUES ('Bob')")
conn.commit() # save changes
except Exception:
conn.rollback() # revert changes on error
finally:
conn.close()
These commands help manage data integrity and ensure atomicity of operations.