8.1 交易處理

交易可用於將作業分組為一個原子單位。當交易提交時,所有作業都會成功,否則都不會成功。只要交易尚未提交,就可以回滾交易。

可以使用 startTransaction() 方法在工作階段中啟動交易,使用 commitTransaction() 提交,並使用 rollbackTransaction() 取消或回滾。以下範例說明了這一點。此範例假設 test 綱要存在,且 my_collection 集合不存在。

var mysqlx = require('mysqlx');

// Connect to server
var session = mysqlx.getSession( {
  host: 'localhost', port: 33060,
  user: 'user', password: 'password' } );

// Get the Schema test
var db = session.getSchema('test');

// Create a new collection
var myColl = db.createCollection('my_collection');

// Start a transaction
session.startTransaction();
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
  session.commit();

  print('Data inserted successfully.');
}
catch (err) {
  // Rollback the transaction in case of an error
  session.rollback();

  // Printing the error message
  print('Data could not be inserted: ' + err.message);
}