PDF (美式信紙) - 1.2Mb
PDF (A4) - 1.2Mb
類似於執行單一陳述式,提交或回滾交易也可能會觸發警告。為了能夠處理這些警告,需要檢查 Session.commit();
或 Session.rollback();
的回覆結果物件。
以下範例會示範此操作。此範例假設測試綱要存在,且集合 my_collection
不存在。
var mysqlx = require('mysqlx');
// Connect to server
var mySession = mysqlx.getSession( {
host: 'localhost', port: 33060,
user: 'user', password: 'password' } );
// Get the Schema test
var myDb = mySession.getSchema('test');
// Create a new collection
var myColl = myDb.createCollection('my_collection');
// Start a transaction
mySession.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
var reply = mySession.commit();
// handle warnings
if (reply.warningCount){
var warnings = reply.getWarnings();
for (index in warnings){
var warning = warnings[index];
print ('Type ['+ warning.level + '] (Code ' + warning.code + '): ' + warning.message + '\n');
}
}
print ('Data inserted successfully.');
}
catch(err)
{
// Rollback the transaction in case of an error
reply = mySession.rollback();
// handle warnings
if (reply.warningCount){
var warnings = reply.getWarnings();
for (index in warnings){
var warning = warnings[index];
print ('Type ['+ warning.level + '] (Code ' + warning.code + '): ' + warning.message + '\n');
}
}
// Printing the error message
print ('Data could not be inserted: ' + err.message);
}
預設情況下,所有警告都會從伺服器傳送至用戶端。如果已知某個操作會產生許多警告,且這些警告對應用程式沒有任何價值,則可以抑制傳送警告。這有助於節省頻寬。session.setFetchWarnings()
會控制是在伺服器上捨棄警告,還是將警告傳送至用戶端。session.getFetchWarnings()
用於了解目前啟用的設定。
var mysqlx = require('mysqlx');
function process_warnings(result){
if (result.getWarningCount()){
var warnings = result.getWarnings();
for (index in warnings){
var warning = warnings[index];
print ('Type ['+ warning.level + '] (Code ' + warning.code + '): ' + warning.message + '\n');
}
}
else{
print ("No warnings were returned.\n");
}
}
// Connect to server
var mySession = mysqlx.getSession( {
host: 'localhost', port: 33060,
user: 'user', password: 'password' } );
// Disables warning generation
mySession.setFetchWarnings(false);
var result = mySession.sql('drop schema if exists unexisting').execute();
process_warnings(result);
// Enables warning generation
mySession.setFetchWarnings(true);
var result = mySession.sql('drop schema if exists unexisting').execute();
process_warnings(result);