X DevAPI 用户指南 / 第 2 章连接和会话概念 /
2.3 使用会话对象
之前的所有示例都使用了Session 对象的getSchema()
或
getDefaultSchema()
方法,它们返回一个 Schema 对象。您使用此 Schema 对象来访问 Collections 和 Tables。大多数示例利用 X DevAPI 的能力来链接所有对象构造,使您能够在一行中获得架构对象。例如:
Press CTRL+C to copyschema = mysqlx.getSession(...).getSchema();
此对象链等同于以下内容,不同之处在于省略了中间步骤:
Press CTRL+C to copysession = mysqlx.getSession(); schema = session.getSchema().
在您获得 Schema 对象之前,不需要始终进行链式调用,它也不总是您想要的。如果要使用 Session 对象,例如调用 Session 对象方法getSchemas()
,则无需向下导航到 Schema。例如:
Press CTRL+C to copysession = 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();