Documentation Home
X DevAPI User Guide
Download this Manual

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

Pre-General Availability Draft: 2018-02-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 server instances running the X Plugin. Sessions are produced by the mysqlx and mysql factories. The mysqlx factory returns NodeSessions, which can encapsulate access to one or more MySQL server instances running X Plugin. Applications that use NodeSession 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. You can supply the connection parameters as either a data dictionary, or as a URI type string.

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 a 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.

MySQL Shell JavaScript Code

var mysqlx = require('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.get_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('@mysql/xdevapi');

// Connect to server on localhost
mysqlx
  .getSession({
    dbUser: 'mike',
    dbPassword: 's3cr3t!',
    host: 'localhost',
    port: '33060'
  })
  .then(function (session) {
    var db = session.getSchema('test');
    // Use the collection 'my_collection'
    var myColl = db.getCollection('my_collection');
    // Specify wich document to find with Collection.find() and
    // fetch it from the database with .execute()
    return myColl
      .find('name like :param')
      .limit(1)
      .bind('param', 'S%')
      .execute(function (doc) {
        console.log(doc);
      });
  })
  .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
Session mySession = new SessionFactory().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();
}

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