2.3 使用会话对象

之前的所有示例都使用了 Session 对象的 getSchema()getDefaultSchema() 方法,它们返回一个 Schema 对象。您可以使用此 Schema 对象访问集合和表。大多数示例都利用了 X DevAPI 将所有对象构造链接起来的能力,使您能够在一行中获得 Schema 对象。例如:

Press CTRL+C to copy
schema = mysqlx.getSession(...).getSchema();

此对象链等效于以下内容,区别在于省略了中间步骤:

Press CTRL+C to copy
session = mysqlx.getSession(); schema = session.getSchema().

没有要求始终链接调用,直到获得 Schema 对象,这也不是您总是想要的。例如,如果您想使用 Session 对象调用 Session 对象方法 getSchemas(),则无需导航到 Schema。例如:

Press CTRL+C to copy
session = mysqlx.getSession(); session.getSchemas().

在此示例中,使用 mysqlx.getSession() 函数打开一个会话。然后使用 Session.getSchemas() 函数获取所有可用模式的列表,并将它们打印到控制台。

Press CTRL+C to copy
// 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();