2.2.1 連線至單一 MySQL 伺服器

在此範例中,使用 MySQL 使用者帳戶 user 及其密碼,建立連線至在本機 MySQL 伺服器執行個體上,於預設 TCP/IP 通訊埠 33060 上執行 X 外掛程式。由於未設定其他參數,因此會使用預設值。

// Passing the parameters in the { param: value } format
var dictSession = mysqlx.getSession( {
        host: 'localhost', 'port': 33060,
        user: 'user', password: 'password' } )

var db1 = dictSession.getSchema('test')

// Passing the parameters in the URI format
var uriSession = mysqlx.getSession('user:password@localhost:33060')

var db2 = uriSession.getSchema('test')

以下範例顯示如何透過提供 TCP/IP 位址 localhost,並使用與之前相同的使用者帳戶連線至單一 MySQL 伺服器執行個體。在這種情況下,系統會提示您輸入使用者名稱和密碼。

// Passing the parameters in the { param: value } format
// Query the user for the account information
print("Please enter the database user information.");
var usr = shell.prompt("Username: ", {defaultValue: "user"});
var pwd = shell.prompt("Password: ", {type: "password"});

// Connect to MySQL Server on a network machine
mySession = mysqlx.getSession( {
        host: 'localhost', 'port': 33060,
        user: usr, password: pwd} );

myDb = mySession.getSchema('test');