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))