2.3 使用 Session 物件

先前的所有範例都使用了 Session 物件的 getSchema()getDefaultSchema() 方法,這些方法會傳回 Schema 物件。您可以使用此 Schema 物件來存取集合和表格。大多數範例都利用 X DevAPI 的能力來鏈接所有物件建構,讓您可以在一行中取得 Schema 物件。例如

schema = mysqlx.getSession(...).getSchema();

此物件鏈等同於以下,不同之處在於省略了中間步驟

session = mysqlx.getSession(); 
schema = session.getSchema().

您不需要總是鏈接呼叫直到取得 Schema 物件,也並非總是您想要的。如果您想要使用 Session 物件,例如,呼叫 Session 物件方法 getSchemas(),則不需要導覽至 Schema。例如

session = mysqlx.getSession(); session.getSchemas().

在此範例中,mysqlx.getSession() 函式用於開啟 Session。然後,Session.getSchemas() 函式用於取得所有可用綱要的清單並將其列印到主控台。

// Connecting to MySQL and working with a Session
var mysqlx = require('mysqlx');

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

// Get a list of all available schemas
var schemaList = mySession.getSchemas();

print('Available schemas in this session:\n');

// Loop over all available schemas and print their name
for (index in schemaList) {
  print(schemaList[index].name + '\n');
}

mySession.close();