文件首頁
X DevAPI 使用者指南
下載本手冊
PDF (美式信紙) - 1.4Mb
PDF (A4) - 1.4Mb


X DevAPI 使用者指南  /  連線與工作階段概念  /  資料庫連線範例

2.1 資料庫連線範例

連線至 MySQL 文件儲存所需的程式碼,看起來很像傳統的 MySQL 連線程式碼,但現在應用程式可以對執行 X Plugin 的 MySQL 伺服器執行個體建立邏輯工作階段。工作階段是由 mysqlx 工廠產生,而傳回的工作階段可以封裝對執行 X Plugin 的一或多個 MySQL 伺服器執行個體的存取。預設使用工作階段物件的應用程式可以部署在單一伺服器設定和資料庫叢集上,而無需變更任何程式碼。

使用 mysqlx.getSession(connection) 方法建立 X DevAPI 工作階段。您將連線參數傳遞至連線的 MySQL 伺服器,例如主機名稱和使用者,這很像其中一個傳統 API 中的程式碼。連線參數可以指定為 URI 類型的字串,例如 user:@localhost:33060,或是資料字典,例如 {user: myuser, password: mypassword, host: example.com, port: 33060}。如需詳細資訊,請參閱使用類似 URI 字串或鍵值組連線至伺服器

用於連線的 MySQL 使用者帳戶應該使用 mysql_native_passwordcaching_sha2_password 驗證外掛程式,請參閱可插入式驗證。您連線的伺服器應已啟用加密連線,這是 MySQL 8.0 和更新版本的預設設定。這可確保用戶端使用 X Protocol PLAIN 密碼機制,此機制適用於使用這兩個驗證外掛程式的使用者帳戶。如果您嘗試連線至未啟用加密連線的伺服器執行個體,對於使用 mysql_native_password 外掛程式的使用者帳戶,會先嘗試使用 MYSQL41 進行驗證,而對於使用 caching_sha2_password 的使用者帳戶,驗證會回復為 SHA256_MEMORY

下列範例程式碼顯示如何連線至 MySQL 伺服器,並從欄位 nameL 開頭的 my_collection 集合取得文件。此範例假設存在名為 test 的結構描述,並且存在 my_collection 集合。若要使此範例正常運作,請將 user 取代為您的使用者名稱,並將 password 取代為您的密碼。如果您要連線至不同的主機或透過不同的連接埠,請將主機從 localhost 和連接埠從 33060 變更。

MySQL Shell JavaScript 程式碼

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

MySQL Shell Python 程式碼

from mysqlsh import mysqlx

# Connect to server on localhost
mySession = mysqlx.get_session( {
        'host': 'localhost', 'port': 33060,
        'user': 'user', 'password': 'password' } )

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', 'L%').execute()

# Print document
document = myDocs.fetch_one()
print(document)

mySession.close()

Node.js JavaScript 程式碼

var mysqlx = require('@mysql/xdevapi');

// Connect to server on localhost
mysqlx
  .getSession({
    user: 'user',
    password: 'password',
    host: 'localhost',
    port: '33060'
  })
  .then(function (session) {
    var db = session.getSchema('test');
    // Use the collection 'my_collection'
    var myColl = db.getCollection('my_collection');
    // Specify which document to find with Collection.find() and
    // fetch it from the database with .execute()
    return myColl
      .find('name like :param')
      .limit(1)
      .bind('param', 'L%')
      .execute(function (doc) {
        console.log(doc);
      });
  })
  .catch(function (err) {
    // Handle error
  });

C# 程式碼

// Connect to server on localhost
var mySession = MySQLX.GetSession("server=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
Console.WriteLine(myDocs.FetchOne());

mySession.Close();

Python 程式碼

import mysqlx

# Connect to server on localhost
my_session = mysqlx.get_session({
     'host': 'localhost', 'port': 33060,
     'user': 'user', 'password': 'password'
 })

my_schema = my_session.get_schema('test')

# Use the collection 'my_collection'
my_coll = my_schema.get_collection('my_collection')

# Specify which document to find with Collection.find() and
# fetch it from the database with .execute()
docs = my_coll.find('name like :param').limit(1).bind('param', 'L%').execute()

# Print document
doc = docs.fetch_one()
print(doc)

my_session.close()

Java 程式碼

import com.mysql.cj.xdevapi.*;

// Connect to server on localhost
Session mySession = new SessionFactory().getSession("mysqlx://127.0.0.1:33060/test?user=user&password=password");

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", "L%").execute();

// Print document
System.out.println(myDocs.fetchOne());

mySession.close();

C++ 程式碼

#include <mysqlx/xdevapi.h>

// Scope controls life-time of objects such as session or schema

{
  Session sess("localhost", 33060, "user", "password");
  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","L%").execute();

  cout << myDocs.fetchOne();
}