8.1 Обработка транзакций
Транзакции могут быть использованы для группирования операций в атомную единицу. Либо все операции транзакции завершаются успешно при их подтверждении, либо ни одна. Возможна отмена транзакции, пока она не подтверждена.
Транзакции могут быть начаты в сессии с помощью метода startTransaction(), подтверждены с помощью commitTransaction() и отменены или откачены с помощью rollbackTransaction(). Это показано в следующем примере. Пример предполагает, что схема test существует, а коллекция my_collection не существует.
from mysqlsh import mysqlx
# Connect to server
mySession = mysqlx.get_session( {
'host': 'localhost', 'port': 33060,
'user': 'user', 'password': 'password' } )
# Get the Schema test
myDb = mySession.get_schema('test')
# Create a new collection
myColl = myDb.create_collection('my_collection')
# Start a transaction
mySession.start_transaction()
try:
myColl.add({'name': 'Rohit', 'age': 18, 'height': 1.76}).execute()
myColl.add({'name': 'Misaki', 'age': 24, 'height': 1.65}).execute()
myColl.add({'name': 'Leon', 'age': 39, 'height': 1.9}).execute()
# Commit the transaction if everything went well
mySession.commit()
print('Data inserted successfully.')
except Exception as err:
# Rollback the transaction in case of an error
mySession.rollback()
# Printing the error message
print('Data could not be inserted: %s' % str(err))
© 2025 Oracle
Licensed under the GPLv2 License.