2.2.1 連線至單一 MySQL 伺服器

在此範例中,將使用 MySQL 使用者帳戶 user 及其密碼,建立連線至在本機執行 X Plugin,並使用預設 TCP/IP 連接埠 33060 的 MySQL 伺服器執行個體。由於未設定其他參數,因此將使用預設值。

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

db1 = dictSession.get_schema('test')

# Passing the parameters in the URI format
uriSession = mysqlx.get_session('user:password@localhost:33060')

db2 = uriSession.get_schema('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.")
usr = shell.prompt("Username: ", {'defaultValue': "user"})
pwd = shell.prompt("Password: ", {'type': "password"})

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

myDb = mySession.get_schema('test')