Beta Draft: 2016-08-16
Table of Contents
This section explains the concepts of connections and sessions as used by the X DevAPI. Code examples for connecting and using sessions are provided.
This section provides an overview of the connection and session concepts used by the X DevAPI. An X Session is a high-level database session concept that is different from working with traditional low-level MySQL connections. X Sessions can encapsulate one or more actual MySQL connections. Use of this higher abstraction level decouples the physical MySQL setup from the application code. An application using the X DevAPI XSession class can be run against a single MySQL server or a group of MySQL servers with no code changes. When a low-level MySQL connection to a single MySQL instance is needed this is still supported by using a low-level NodeSession.
Before looking at the XSession and NodeSession concepts in more detail, the following examples show that working with a database remains easy.
The code that is needed to connect to a MySQL document store looks
a lot like the traditional MySQL connection code, but now
applications can establish logical sessions to MySQL nodes running
the X Plugin. Sessions are produced by the
mysqlx factory. The factory returns two types
of Sessions. An XSession encapsulates access to a single MySQL
server running the X Plugin or multiple nodes of cluster. A
NodeSession serves as an abstraction for a physical connection to
exactly one MySQL server running the X Plugin. It is
recommended to use the mysqlx.getSession()
method to obtain an XSession object. Applications that use
XSession objects by default can be deployed on both single server
setups and database clusters with no code changes. The method
expects a list of connection parameters, very much like the code
in one of the classic APIs.
The following example code shows how to connect to a MySQL server
and get a document from the my_collection that
has the field name starting with
S. The example assumes that schema called test
exists, and the my_collection collection exists. To make the
example work, replace mike with your username,
and s3cr3t! with your password. If you are
connecting to a different host or through a different port, change
the host from localhost and the port from
33060 .
Please note that MySQL Shell JavaScript and Python code examples are specific to MySQL Shell and rely mostly on the exception handling done by MySQL Shell. For all other languages proper exception handling is required to catch errors. For more information see: Section 8.2, “Error Handling”.
MySQL Shell JavaScript Code
var mysqlx = require('mysqlx').mysqlx;
// Connect to server on localhost
var mySession = mysqlx.getSession( {
host: 'localhost', port: 33060,
dbUser: 'mike', dbPassword: 's3cr3t!' } );
var myDb = mySession.getSchema('test');
// Use the collection 'my_collection'
var myColl = myDb.getCollection('my_collection');
// Specify which document to find with Collection.find() and
// fetch it from the database with .execute()
var myDocs = myColl.find('name like :param').limit(1).
bind('param', 'S%').execute();
// Print document
print(myDocs.fetchOne());
mySession.close();
MySQL Shell Python Code
import mysqlx
# Connect to server on localhost
mySession = mysqlx.getSession( {
'host': 'localhost', 'port': 33060,
'dbUser': 'mike', 'dbPassword': 's3cr3t!' } )
myDb = mySession.getSchema('test')
# Use the collection 'my_collection'
myColl = myDb.getCollection('my_collection')
# Specify which document to find with Collection.find() and
# fetch it from the database with .execute()
myDocs = myColl.find('name like :param').limit(1).bind('param', 'S%').execute()
# Print document
document = myDocs.fetchOne()
print document
mySession.close()
Node.js JavaScript Code
var mysqlx = require('mysqlx');
// Connect to server on localhost
mysqlx.getSession( {
host: 'localhost', port: '33060',
dbUser: 'mike', dbPassword: 's3cr3t!'
}).then(function(session) {
return session.getSchema('test');
}).then(function (db) {
// Use the collection 'my_collection'
var myColl = db.getCollection('my_collection');
// Specify with document to find with Collection.find() and
// fetch it from the database with .execute()
return myColl.find('name like :1').limit(1).bind('S*').execute(function (document) {
console.log(document);
});
}).catch(function (err) {
// Handle error
});
C# Code
// Connect to server on localhost
var mySession = MySqlX.GetSession("server=localhost;port=33060;user=mike;password=s3cr3t!;");
var myDb = mySession.GetSchema("test");
// Use the collection "my_collection"
var myColl = myDb.GetCollection("my_collection");
// Specify with document to find with Collection.find() and
// fetch it from the database with .execute()
var myDocs = myColl.Find("name like :param").Limit(1)
.Bind("param", "S%").Execute();
// Print document
Console.WriteLine(myDocs.FetchOne());
mySession.Close();
Java Code
import com.mysql.cj.api.x.*;
import com.mysql.cj.x.MysqlxSessionFactory;
// Connect to server on localhost
String url = "mysqlx://localhost:33060/test?user=mike&password=s3cr3t!"
XSession mySession = new MysqlxSessionFactory().getSession(url);
Schema myDb = mySession.getSchema("test");
// Use the collection 'my_collection'
Collection myColl = myDb.getCollection("my_collection");
// Specify which document to find with Collection.find() and
// fetch it from the database with .execute()
DocResult myDocs = myColl.find("name like :param").limit(1)
.bind("param", "S%").execute();
// Print document
System.out.println(myDocs.fetchOne());
mySession.close();
C++ Code
// note: header name mysqlx.h reserved for Connector/C
#include <mysqlx.h>
// Scope controls life-time of objects such as session or schema
{
XSession sess("localhost", 33060, "mike", "s3cr3t!");
Schema db= sess.getSchema("test");
// or Schema db(sess, "test");
Collection myColl = db.getCollection("my_collection");
// or Collection myColl(db, "my_collection");
DocResult myDocs = myColl.find("name like :param")
.limit(1)
.bind("param","S%").execute();
cout << myDocs.fetchOne();
}
By writing MySQL Shell code to a file, such as
test.js (or test.py),
you can then execute the code from MySQL Shell.
# Launch the MySQL Shell and execute the script $ mysqlsh < test.js
For more information on MySQL Shell, see MySQL Shell User Guide.
This section provides an overview of the XSession and NodeSession objects. The difference between XSession and NodeSession is that XSession abstracts the connection, meaning that it can be a connection to one or more MySQL Servers. A NodeSession does not abstract the connection and connects directly to only a single MySQL Server. An XSession is the default when connecting from MySQL Shell. This logical abstraction enables you to address a group of servers without requiring code changes. The following table illustrates the advantages of coding using XSession.
Feature | XSession | NodeSession |
|---|---|---|
Session Type | Logical | Physical |
Document support | ✓ | ✓ |
Relational Table support | ✓ | ✓ |
Full SQL Language support | - | ✓ |
The following features are available:
Feature | XSession | NodeSession |
|---|---|---|
Session Type | Logical | Physical |
Document support | ✓ | ✓ |
Relational Table support | ✓ | ✓ |
Transparent HA support | - | - |
Vertical scaling support | - | - |
Horizontal scaling support | - | - |
Full SQL Language support | - | ✓ |
MySQL Shell offers an additional ClassicSession class which can be used to execute SQL on MySQL Servers not running X Plugin, see also Section 13.2, “MySQL Shell X DevAPI extensions”.
The following class diagram gives an overview of the most important classes when working with a MySQL document store.
Modern database applications often have to deal with a high number of reads and/or writes per second. This is why it is important to be able to scale the database to deal with increasing load. Even projects that are not initially designed with scaleout in mind may have to grow quickly if they become successful. Therefore it is very important that the database can be scaled at any point in time without having to rewrite the application code.
Using the XSession concept enables you to write code that can be scaled without changing any object. This could be used for transparent High availability (HA), vertical scaleout (database replication) and horizontal scaleout (sharding) for database applications. Although the current version of MySQL X supports XSessions that connect to a single node, future versions could extend this to cover multiple nodes. An application using XSession is prepared to be scaled: change some connect parameters and be done with code changes. An application using NodeSession establishes connections to individual nodes. To scale an application using NodeSession you would have to replace the use of NodeSession with XSession whenever possible. This is likely going to be more coding work than updating some connect parameters.Therefore it is strongly recommended to use XSessions wherever possible.
There are several ways of connecting to a session depending on the specific setup in use. This section explains the different methods available.
In some cases, like prototyping or applications running against a single MySQL Server, it can be helpful to directly specify the host explicitly in the connection string. The following examples show how this is done.
In this example a connection to a local MySQL Server running X Plugin on the default TCP/IP port 33060 is established using the MySQL user account "mike" with the password "s3cr3t!". As no other parameters are set, default values are used.
MySQL Shell JavaScript Code
// Passing the parameters in the { param: value } format
var dictSession = mysqlx.getSession( {
host: 'localhost',
port: 33060,
dbUser: 'mike',
dbPassword: 's3cr3t!' } );
var db1 = dictSession.getSchema('test');
// Passing the parameters in the URL format
var uriSession = mysqlx.getSession('mike:s3cr3t!@localhost:33060');
var db2 = uriSession.getSchema('test');
MySQL Shell Python Code
# Passing the parameters in the { param: value } format
dictSession = mysqlx.getSession( {
'host': 'localhost', 'port': 33060,
'dbUser': 'mike', 'dbPassword': 's3cr3t!' } )
db1 = dictSession.getSchema('test')
# Passing the parameters in the URL format
uriSession = mysqlx.getSession('mike:s3cr3t!@localhost:33060')
db2 = uriSession.getSchema('test')
The following example shows how to connect to a single MySQL Server by providing a TCP/IP address “localhost” and the same user account as before. You are prompted to enter the username and password in this case.
MySQL Shell JavaScript Code
// Passing the parameters in the { param: value } format
// Query the use for the user information
print("Please enter the database user information.");
var usr = prompt("Username: ", {defaultValue: "mike"});
var pwd = prompt("Password: ", {type: "password"});
// Connect to MySQL Server running X Plugin on a network machine
var mySession = mysqlx.getSession( {
host: 'localhost', port: 33060,
dbUser: usr, dbPassword: pwd} );
var myDb = mySession.getSchema('test');
MySQL Shell Python Code
# Passing the parameters in the { param: value } format
# Query the user for the account information
print "Please enter the database user information."
usr = shell.prompt("Username: ", {'defaultValue': "mike"})
pwd = shell.prompt("Password: ", {'type': "password"})
# Connect to MySQL Server on a network machine
mySession = mysqlx.getSession( {
'host': 'localhost', 'port': 33060,
'dbUser': usr, 'dbPassword': pwd} )
myDb = mySession.getSchema('test')
C# Code
// Passing the parameters in the { param: value } format
// Query the use for the user information
Console.WriteLine("Please enter the database user information.");
Console.Write("Username: ");
var usr = Console.ReadLine();
if (string.IsNullOrEmpty(usr)) usr = "mike";
Console.Write("Password: ");
var pwd = Console.ReadLine();
if (string.IsNullOrEmpty(pwd)) pwd = "s3cr3t!";
// Connect to MySQL Server on a network machine
var mySession = MySqlX.GetSession(string.Format("host=localhost; port=33060; User={0}; Password={1};", usr, pwd));
var myDb = mySession.GetSchema("test");
Java Code
import com.mysql.cj.api.x.*;
import com.mysql.cj.x.MysqlxSessionFactory;
// Connect to server on localhost using a connection URL
String url = "mysqlx://localhost:33060/test?user=mike&password=s3cr3t!"
XSession mySession = new MysqlxSessionFactory().getSession(url);
Schema myDb = mySession.getSchema("test");
C++ Code
// Assuming prompt_user() is a function which does interaction with the user.
string user;
string password;
prompt_user("Please enter the database user information", user, password);
// Note: Connector/C++ does not support connection string or connection settings
// in a form of dictionary.
XSession mySession("localhost", 33060, user, password).getSchema("test");
auto myDb = mySession.getSchema("test");
C Code
The only transport protocol which is supported is TCP/IP. SSL support is not included in the first release.
When using a Session the following options are available to configure the connection.
Option | Name | Optional | Default | Notes |
|---|---|---|---|---|
TCP/IP Host | host | - | localhost, IPv4 host name, no IP-range | |
TCP/IP Port | port | ✓ | 33060 | Standard X Plugin port is 33060 |
MySQL user | dbUser | - | MySQL database user | |
MySQL password | dbPassword | - | The MySQL user's password |
Supported password encryptions are:
MYSQL 4.1
URI elements and format.
ConnectURI1::= 'dbUser' ':' 'dbPassword' '@' 'host' ':' 'port'
All previous examples used the getSchema() or
getDefaultSchema() methods of the Session
object, which return a Schema object. You use this Schema to
access Collections and Tables. Most examples make use of the
X DevAPI ability to chain all object constructions,
enabling you to get to the schema object in one line. For
example:
schema = mysqlx.getSession(...).getSchema();
This object chain is equivalent to the following, with the difference that the intermediate step is omitted:
session = mysqlx.getSession(); schema = session.getSchema().
There is no requirement to always chain calls until you get a
Schema object, neither is it always what you want. If you want
to work with the Session object, for example, to call the
Session object method getSchemas(), there is
no need to navigate down to the Schema. For example:
session = mysqlx.getSession(); session.getSchemas().
MySQL Shell JavaScript Code
// Connecting to MySQL and working with a Session
var mysqlx = require('mysqlx').mysqlx;
// Connect to a dedicated MySQL server using a connection URL
var mySession = mysqlx.getSession('mike:s3cr3t!@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();
MySQL Shell Python Code
# Connecting to MySQL and working with a Session
import mysqlx
# Connect to a dedicated MySQL server using a connection URL
mySession = mysqlx.getSession('mike:s3cr3t!@localhost')
# Get a list of all available schemas
schemaList = mySession.getSchemas()
print 'Available schemas in this session:\n'
# Loop over all available schemas and print their name
for schema in schemaList:
print '%s\n' % schema.name
mySession.close()
Node.js JavaScript Code
// Connecting to MySQL and working with a Session
var mysqlx = require('mysqlx').mysqlx;
// Connect to a dedicated MySQL server using a connection URL
mysqlx.getSession('mike:s3cr3t!@localhost').then(function (mySession) {
// Get a list of all available schemas
return mySession.getSchemas();
}).then(function (schemaList) {
console.log('Available schemas in this session:\n');
// Loop over all available schemas and print their name
for (schema in schemaList) {
console.log(schema + '\n');
}
});
C# Code
// Connect to a dedicated MySQL server node using a connection URL
var mySession = MySqlX.GetSession("server=localhost;port=33060;user=mike;password=s3cr3t!;");
// Get a list of all available schemas
var schemaList = mySession.GetSchemas();
Console.WriteLine("Available schemas in this session:");
// Loop over all available schemas and print their name
foreach (var schema in schemaList)
{
Console.WriteLine(schema);
}
mySession.Close();
Java Code
import com.mysql.cj.api.x.*;
import com.mysql.cj.x.MysqlxSessionFactory;
// Connecting to MySQL and working with a Session
// Connect to a dedicated MySQL server using a connection URL
String url = "mysqlx://localhost:33060/test?user=mike&password=s3cr3t!"
XSession mySession = new MysqlxSessionFactory().getSession(url);
// Get a list of all available schemas
List<Schema> schemaList = mySession.getSchemas();
System.out.println("Available schemas in this session:");
// Loop over all available schemas and print their name
for (Schema schema : schemaList) {
System.out.println(schema);
}
mySession.close();
C++ Code
#include <mysqlx.h>
// Connecting to MySQL and working with a Session
// Connect to a dedicated MySQL server node
XSession mySession("localhost", 33060, "mike", "s3kr3t!");
// Get a list of all available schemas
std::list<Schema> schemaList = mySsession.getSchemas();
// Loop over all available schemas and print their name
cout <<"Available schemas in this session: " <<endl;
for (auto schema : schemaList)
{
cout <<schema.name() <<endl;
}
In this example the mysqlx.getSession()
function is used to open a Session. Then the
Session.getSchemas() function is used to get
a list of all available schemas and print them to the console.
When using an XSession, a simplified X DevAPI syntax is used for SQL queries. This exposes a sub-set of SQL that can be used in transparent high availability, replication, and sharding environments.
In some cases access to the full SQL language is needed, for
example to directly connect to a specific MySQL Server to do
operations specifically on this server. In those cases a direct,
low-level connection needs to be opened. This is performed by
using the mysqlx.getNodeSession() function,
which returns a NodeSession object.
The mysqlx.getNodeSession() function can take a
URL that specifies the connection information for a specific
server or it can take a configuration provided by a Session.
In addition to the simplified X DevAPI syntax of the
Session object, the NodeSession object has a
sql() function that takes any SQL statement
as a string.
The following example uses a NodeSession to call an SQL Stored Procedure on the specific node.
MySQL Shell JavaScript Code
var mysqlx = require('mysqlx').mysqlx;
// Connect to server using a NodeSession
var mySession = mysqlx.getNodeSession('mike:s3cr3t!@localhost');
// Switch to use schema 'test'
mySession.sql("USE test").execute();
// In a NodeSession 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();
MySQL Shell Python Code
import mysqlx
# Connect to server using a NodeSession
mySession = mysqlx.getNodeSession('mike:s3cr3t!@localhost')
# Switch to use schema 'test'
mySession.sql("USE test").execute()
# In a NodeSession 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.fetchOne()
print row[0]
mySession.close()
Node.js JavaScript Code
var mysqlx = require('mysqlx');
// Connect to server using a Low-Level NodeSession
mysqlx.getNodeSession('root:s3kr3t@localhost').then(function(session) {
return session.getSchema('test');
}).then(function(nodeDb) {
return Promise.all([
// Switch to use schema 'test'
nodeDb.executeSql("USE test").execute(),
// In a NodeSession context the full SQL language can be used
nodeDb.executeSql("CREATE PROCEDURE my_add_one_procedure " +
" (INOUT incr_param INT) " +
"BEGIN " +
" SET incr_param = incr_param + 1;" +
"END;").execute(),
nodeDb.executeSql("SET @my_var = ?;", 10).execute(),
nodeDb.executeSql("CALL my_add_one_procedure(@my_var);").execute(),
nodeDb.executeSql("DROP PROCEDURE my_add_one_procedure;").execute()
]).then(function() {
// Use an SQL query to get the result
return nodeDb.executeSql("SELECT @my_var");
}).then(function(my_result) {
// Print result
console.log(my_result);
});
});
C# Code
// Connect to server using a NodeSession
var mySession = MySqlX.GetNodeSession("server=localhost;port=33060;user=mike;password=s3cr3t!;");
// Switch to use schema "test"
mySession.SQL("USE test").Execute();
// In a NodeSession 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 = 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();
Console.WriteLine(row[0]);
mySession.Close();
Java Code
import com.mysql.cj.api.x.*;
import com.mysql.cj.x.MysqlxSessionFactory;
// Connect to server on localhost
String url = "mysqlx://localhost:33060/test?user=mike&password=s3cr3t!"
NodeSession mySession = new MysqlxSessionFactory().getNodeSession(url);
// Switch to use schema 'test'
mySession.executeSql("USE test");
// In a NodeSession 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
SqlResult myResult = mySession.sql("SELECT @my_var").execute();
// Gets the row and prints the first column
Row row = myResult.fetchOne();
System.out.println(row.getInt(0));
mySession.close();
C++ Code
#include <mysqlx.h>
// Connect to localhost using a Low-Level NodeSession
NodeSession mySession(33060, "mike", "s3kr3t!");
// Switch to use schema 'test'
mySession.sql("USE test").execute();
// In a NodeSession 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.aql("DROP PROCEDURE my_add_one_procedure;").execute();
// Use an SQL query to get the result
auto myResult = session.sql("SELECT @my_var").execute();
// Gets the row and prints the first column
Row row = myResult.fetchOne();
print(row[0]);
As mentioned previously, literal/verbatim SQL can only be issued when connected to one node. Only the NodeSession class includes a function sql(). The XSession class does not because it encapsulates a connection to many nodes. When connected to multiple MySQL Servers, additional tasks arise over the single node case. Among these tasks is failover. The standard query language allows users to establish a stateful connection. Transparently failing over a stateful connection is a difficult and complex task. The X DevAPI XSession class implements a significant subset of the SQL language through API calls. The API calls offered do not allow building a connection state. This is a key enabler for automatic and transparent failover. Future versions of the X DevAPI might support literal SQL when working with the XSession class. Note that you are not cut off from using the full power of SQL but literal/verbatim SQL is only available with NodeSession based connections.
When using literal/verbatim SQL the common API patterns are mostly the same compared to using DML and CRUD operations on Tables and Collections. Two differences exist: setting the current schema and escaping names.
A newly opened session has no schema set. There is no concept of an implicitly set default schema when a session is established. A default schema can be defined, but a session's current schema is not set to a default before being explicitly selected.
An explicit schema selection happens as part of using the CRUD
functions of the X DevAPI. For example, Table and
Collection objects are created by Schema objects. Schema
objects, in turn, are created by Session objects. To insert rows
into a table, call
session.getSchema().getTable().insert(). To
add a document to a collection from the default schema, call
session.getDefaultSchema().getCollection().add().
The sql() function is a method of the
NodeSession class but not the Schema class. Upon creation, the
NodeSession class has no schema selected by default. Therefore,
the sql() function does not know which schema
to execute the SQL statement against. Use the Session class
setCurrentSchema() function to set or change
the current schema.
MySQL Shell JavaScript Code
var mysqlx = require('mysqlx').mysqlx;
// Direct connect with no client side default schema defined
var mySession = mysqlx.getNodeSession('mike:s3cr3t!@localhost');
mySession.setCurrentSchema("test");
MySQL Shell Python Code
import mysqlx
# Direct connect with no client side default schema defined
mySession = mysqlx.getNodeSession('mike:s3cr3t!@localhost')
mySession.setCurrentSchema("test")
Node.js JavaScript Code
C# Code
// Direct connect with no client side default schema defined
var mySession = MySqlX.GetNodeSession("server=localhost;port=33060;user=mike;password=s3cr3t!;");
mySession.GetSchema("test");
var session = MySqlX.GetNodeSession("server=localhost;port=33060;user=mike;password=s3cr3t!;");
var default_schema = session.GetSchema("test");
// print the current schema name
Console.WriteLine(session.Schema.Name);
private Table CreateTestTable(NodeSession session, string name)
// use escape function to quote names/identifier
string quoted_name = "`" + name + "`";
session.SQL("DROP TABLE IF EXISTS " + quoted_name).Execute();
var create = "CREATE TABLE ";
create += quoted_name;
create += " (id INT NOT NULL PRIMARY KEY AUTO_INCREMENT)";
session.SQL(create).Execute();
return session.Schema.GetTable(name);
}
Java Code
import com.mysql.cj.api.x.*; import com.mysql.cj.x.MysqlxSessionFactory; // Schema 'test' set in connection URL String url = "mysqlx://localhost:33060/test?user=mike&password=s3cr3t!" NodeSession mySession = new MysqlxSessionFactory().getNodeSession(url);
C++ Code
#include <mysqlx.h>
// When creating session no client side default schema is defined
NodeSession mySession(33060, "mike", "s3kr3t!");
// The .setCurrentSchema() method is not yet implemented, current
// schema can be set only using direct SQL statement.
mySession.sql("USE test").execute();
C Code
A quoting function exists to escape SQL names and identifiers.
NodeSession.quoteName() escapes the
identifier given in accordance to the settings of the current
connection. The escape function must not be used to escape
values. Use the value bind syntax of
NodeSession.sql() instead.
MySQL Shell JavaScript Code
function createTestTable(session, name) {
// use escape function to quote names/identifier
quoted_name = session.quoteName(name);
session.sql("DROP TABLE IF EXISTS " + quoted_name).execute();
var create = "CREATE TABLE ";
create += quoted_name;
create += " (id INT NOT NULL PRIMARY KEY AUTO_INCREMENT)";
session.sql(create).execute();
return session.getCurrentSchema().getTable(name);
}
var mysqlx = require('mysqlx').mysqlx;
var session = mysqlx.getNodeSession({
dataSourceFile: 'mysqlxconfig.json', app: 'myapp',
dbUser: 'mike', dbPassword: 's3cr3t!'});
var default_schema = session.getDefaultSchema().name;
session.setCurrentSchema(default_schema);
// Creates some tables
var table1 = createTestTable(session, 'test1');
var table2 = createTestTable(session, 'test2');
MySQL Shell Python Code
def createTestTable(session, name):
# use escape function to quote names/identifier
quoted_name = session.quoteName(name)
session.sql("DROP TABLE IF EXISTS " + quoted_name).execute()
create = "CREATE TABLE "
create += quoted_name
create += " (id INT NOT NULL PRIMARY KEY AUTO_INCREMENT)"
session.sql(create).execute()
return session.getCurrentSchema().getTable(name)
import mysqlx
session = mysqlx.getNodeSession({
'dataSourceFile': 'mysqlxconfig.json', 'app': 'myapp',
'dbUser': 'mike', 'dbPassword': 's3cr3t!'})
default_schema = session.getDefaultSchema().name
session.setCurrentSchema(default_schema)
# Creates some tables
table1 = createTestTable(session, 'test1')
table2 = createTestTable(session, 'test2')
Node.js JavaScript Code
function createTestTable(session, name) {
// use escape function to quote names/identifier
quoted_name = session.quoteName(name);
session.executeSql("DROP TABLE IF EXISTS " + quoted_name).execute();
var create = "CREATE TABLE ";
create += quoted_name;
create += " (id INT NOT NULL PRIMARY KEY AUTO_INCREMENT)";
session.executeSql(create).execute();
return session.getCurrentSchema().getTable(name);
}
var mysqlx = require('mysqlx').mysqlx;
mysqlx.getNodeSession({
dataSourceFile: 'mysqlxconfig.json', app: 'myapp',
dbUser: 'mike', dbPassword: 's3cr3t!'
}).then(function (session) {
session.executeSql("use myschema").execute();
var default_schema = session.getDefaultSchema().name;
session.setCurrentSchema(default_schema);
// Creates some tables
var table1 = createTestTable(session, 'test1');
var table2 = createTestTable(session, 'test2');
session.close();
});
C# Code
var session = MySqlX.GetNodeSession("server=localhost;port=33060;user=mike;password=s3cr3t!;");
session.SQL("use test;").Execute();
session.GetSchema("test");
// Creates some tables
var table1 = CreateTestTable(session, "test1");
var table2 = CreateTestTable(session, "test2");
Java Code
Java does not currently support the quoteName() method.
C++ Code
#include <mysqlx.h>
// Note: The following features are not yet implemented by
// Connector/C++:
// - DataSoure configuration files,
// - setCurrentSchema()/getCurrentSchema() methods,
// - quoteName() method.
Table createTestTable(Schema &schema, const string &name)
{
Session &session = schema.getSession();
string quoted_name = string("`") + schema.getName() + "`.`" name + "`";
session.sql(string("DROP TABLE IF EXISTS") + quoted_name).execute();
string create = "CREATE TABLE ";
create += quoted_name;
create += "(id INT NOT NULL PRIMARY KEY AUTO_INCREMENT");
session.sql(create).execute();
return schema.getTable(name);
}
NodeSession session(33060, "mike", "s3cr3t!");
Schema schema = session.getSchema("test");
Table table1 = createTestTable(schema, "test1");
Table table2 = createTestTable(schema, "test2");
Users of the X DevAPI do not need to escape identifiers. This is true for working with collections and for working with relational tables.