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
factory, and the returned sessions can
encapsulate access to one or more MySQL server instances running
X Plugin. Applications that use Session objects by default can be
deployed on both single server setups and database clusters with
no code changes.
Create an X DevAPI session using the
mysqlx.getSession(connection)
method. You pass
in the connection parameters to connect to the MySQL server, such
as the hostname and user, very much like the code in one of the
classic APIs. The connection parameters can be specified as either
a URI type string, for example
user:@localhost:33060
, or as a data dictionary,
for example {user: myuser, password: mypassword, host:
example.com, port: 33060}
. See
Connecting to the Server Using URI-Like Strings or Key-Value Pairs for more
information.
The MySQL user account used for the connection should use either
the mysql_native_password
or
caching_sha2_password
authentication plugin,
see Pluggable Authentication. The server you are
connecting to should have encrypted connections enabled, the
default in MySQL 8.0 and later. This ensures that the client uses
the X Protocol PLAIN
password mechanism which
works with user accounts that use either of the authentication
plugins. If you try to connect to a server instance which does not
have encrypted connections enabled, for user accounts that use the
mysql_native_password
plugin authentication is
attempted using MYSQL41
first, and for user
accounts that use caching_sha2_password
authentication falls back to SHA256_MEMORY
.
The following example code shows how to connect to a MySQL server
and get a document from the my_collection
collection that has the field name
starting
with L
. The example assumes that a schema
called test
exists, and the
my_collection
collection exists. To make the
example work, replace user
with your username,
and
with
your password. If you are connecting to a different host or
through a different port, change the host from
password
localhost
and the port from
33060
.
var mysqlx = require('mysqlx');
// Connect to server on localhost
var mySession = mysqlx.getSession( {
host: 'localhost', port: 33060,
user: 'user', password: 'password' } );
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', 'L%').execute();
// Print document
print(myDocs.fetchOne());
mySession.close();