2.4 使用 Session 執行 SQL

除了 Session 物件的簡化 X DevAPI 語法之外,Session 物件還有一個 sql() 函數,它會將任何 SQL 陳述式作為字串。

以下範例使用 Session 在特定節點上呼叫 SQL 預存程序。

var mysqlx = require('mysqlx');

// Connect to server using a Session
var mySession = mysqlx.getSession('user:password@localhost');

// Switch to use schema 'test'
mySession.sql("USE test").execute();

// In a Session context the full SQL language can be used
mySession.sql("CREATE PROCEDURE my_add_one_procedure " +
  " (INOUT incr_param INT) " +
  "BEGIN " +
  "  SET incr_param = incr_param + 1;" +
  "END;").execute();
mySession.sql("SET @my_var = ?;").bind(10).execute();
mySession.sql("CALL my_add_one_procedure(@my_var);").execute();
mySession.sql("DROP PROCEDURE my_add_one_procedure;").execute();

// Use an SQL query to get the result
var myResult = mySession.sql("SELECT @my_var").execute();

// Gets the row and prints the first column
var row = myResult.fetchOne();
print(row[0]);

mySession.close();

當使用文字/逐字 SQL 時,與在資料表和集合上使用 DML 和 CRUD 操作相比,常見的 API 模式大多相同。存在兩個差異:設定目前的 schema 和跳脫名稱。