2.4 使用 SQL 與 Session

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

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

from mysqlsh import mysqlx

# Connect to server using a Session
mySession = mysqlx.get_session('user:password@localhost')

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

# In a Session context the full SQL language can be used
sql = """CREATE PROCEDURE my_add_one_procedure
                                 (INOUT incr_param INT)
                                 BEGIN
                                         SET incr_param = incr_param + 1;
                                 END
                        """

mySession.sql(sql).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
myResult = mySession.sql("SELECT @my_var").execute()

# Gets the row and prints the first column
row = myResult.fetch_one()
print(row[0])

mySession.close()

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