Documentation Home
X DevAPI User Guide
Download this Manual

X DevAPI User Guide  /  Connection and Session Concepts  /  Database Connection Example

Pre-General Availability Draft: 2017-07-20

2.1 Database Connection Example

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 .

Note

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');

// Connect to server on localhost
var mySession = mysqlx.getNodeSession( {
                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.get_node_session( {
        'host': 'localhost', 'port': 33060,
        'dbUser': 'mike', 'dbPassword': 's3cr3t!' } )

myDb = mySession.get_schema('test')

# Use the collection 'my_collection'
myColl = myDb.get_collection('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.fetch_one()
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.xdevapi.*;
import com.mysql.cj.xdevapi.*;

// Connect to server on localhost
XSession mySession = new XSessionFactory().getSession("mysqlx://localhost:33060/test?user=mike&password=s3cr3t!");

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

#include <mysql_devapi.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.


User Comments
Sign Up Login You must be logged in to post a comment.