連接外部應用程式

您的應用程式及驅動程式會使用連線字串來建立與 IBM Cloud® Databases for MySQL的連線。 該服務特別為驅動程式和應用程式提供連線字串。 連線字串會顯示在部署 概觀的 端點 畫面中,也可以從 Cloud DatabasesCLI 外掛程式 及 Cloud Databases API 中擷取。

您在部署上建立的任何認證都可以使用連線字串。 雖然您可以針對所有連線及應用程式使用管理使用者,但最好特別為您的應用程式建立使用者以進行連接。 有關產生憑證的文件位於 建立使用者和取得連接字串 頁面。

使用語言的驅動程式連接

驅動程式建立與部署的連線所需的所有資訊都位於連線字串的 "mysql" 區段中。 表格包含參照的明細。

mysql/URI 連線訊息
欄位名稱 索引 說明
Type 連線類型 - MySQL, 是「URI」。
Scheme URI 的方案 - MySQL, 是 "mysql"。
Path URI 的路徑 - 對於MySQL,它是資料庫名稱。 預設為 ibmclouddb。
Authentication Username 您用來連接的使用者名稱。
Authentication Password 使用者的密碼 - 可能會顯示為 $PASSWORD。
Authentication Method 如何進行鑑別; 由驅動程式處理「直接」鑑別。
Hosts 0... 要連線的主機名稱和連接埠。
Composed 0... 結合 Scheme、Authentication、Host 及 Path 的 URI。
Certificate Name 用於資料庫部署的服務專屬憑證的已分配名稱。
Certificate Base64 憑證的 base64 編碼版本。
  • 0... 指出陣列中的一或多個這些項目。

如果在連線資訊的 "composed" 欄位中找到 URI 格式的連線字串,則許多 MySQL 驅動程式都可以建立與部署的連線。 舉例來說,

mysql://ibm_cloud_30399dec_4835_4967_a23d_30587a08d9a8:$PASSWORD@981ac415-5a35-4ac7-b6bb-fb609326dc42.8f7bfd8f3faa4218aec56e069eb46187.databases.appdomain.cloud:32704/ibmclouddb?ssl-mode=verify-full

如需 ssl-mode 狀態的相關資訊,請參閱 其他連線參數。

下列範例使用連線字串及 Java 驅動程式 jdbc 中的資訊來連接至資料庫。

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

public class App {
 private final String STATUS_COMMAND = "SHOW VARIABLES LIKE '%version%';";

 private Connection connect = null;
 private Statement stmt = null;
 private ResultSet rs = null;

 private final String url = "mysql://127.0.0.1:30799";
 private final String username = "";
 private final String password = "";
 private final Boolean useSSL = true;

 public static void main(String args[]) throws Exception {
   App app = new App();
   final byte maxConnectionAttempt = 5;
   byte currentConnectionAttempt = 0;

   while (!app.connectDatabase() && currentConnectionAttempt < maxConnectionAttempt)
      ++currentConnectionAttempt;

   if (currentConnectionAttempt >= maxConnectionAttempt) {
      System.out.println(currentConnectionAttempt + " weren't successfull!");
         } else {
            app.printStatus();
            app.closeConnection();
         }
   }

   public void printStatus() {
         try {
            stmt = connect.createStatement();
            rs = stmt.executeQuery(STATUS_COMMAND);
            while (rs.next())
            System.out.println(rs.getString(1) + ": " + rs.getString(2));
         } catch (SQLException ex) {
            System.out.println("SQLException: " + ex.getMessage());
            System.out.println("SQLState: " + ex.getSQLState());
            System.out.println("VendorError: " + ex.getErrorCode());
            closeConnection();
         }
   }

   private void closeConnection() {
      try {
         if (rs != null) {
            rs.close();
         }

         if (stmt != null) {
            stmt.close();
         }

         if (connect != null) {
            connect.close();
         }
      } catch (Exception e) {
         System.out.println(e.getMessage());
      }
      System.out.println("Connection closed.");
   }

   public boolean connectDatabase() {
      // https://dev.mysql.com/doc/connector-j/8.0/en/connector-j-usagenotes-connect-drivermanager.html
      try {
            Properties props = new Properties();
            props.setProperty("user", username);
            props.setProperty("password", password);
            props.setProperty("useSSL", Boolean.toString(useSSL));
            props.setProperty("sslMode", (useSSL ? "REQUIRED" : "DISABLED"));
            props.setProperty("requireSSL", Boolean.toString(useSSL));
            props.setProperty("verifyServerCertificate", Boolean.toString(useSSL));

            Class.forName("com.mysql.cj.jdbc.Driver");
            connect = DriverManager.getConnection("jdbc:" + url, props);
            return true;
      } catch (SQLException ex) {
            System.out.println("SQLException: " + ex.getMessage());
            System.out.println("SQLState: " + ex.getSQLState());
            System.out.println("VendorError: " + ex.getErrorCode());
      } catch (ClassNotFoundException ex) {
            System.out.println("Connector class can not be found: " + ex.getMessage());
      }
      return false;
   }
}

下列範例使用連線字串及 Python 驅動程式 pymysql 中的資訊來連接至資料庫。 這只是簡單的連線範例,沒有錯誤處理或重試邏輯,可能不適用於正式作業。

import pymysql
connection = pymysql.connect(
  host="hostname",
  port=32089,
  user="username",
  passwd="password",
  ssl_ca="/home/user/mysql_ca.crt",
  ssl_verify_cert=True,
  ssl_verify_identity=True)

cursor = connection.cursor()
cursor.execute("SHOW STATUS;")

for row in cursor:
    print(row[0] + "\t" + row[1])

cursor.close()
connection.close()

驅動程式 TLS 和服務專屬憑證支援

Databases for MySQL 的所有連線都已啟用 TLS 1.2,因此您用來連接的驅動程式必須能夠支援加密。 您的部署還隨附服務專屬憑證,因此驅動程式可以在連線時驗證伺服器。

如需相關資訊,請參閱 Cloud Databases 憑證常見問題(FAQ)。

使用服務專屬憑證

  1. 從 端點 畫面或連線資訊的 Base64 欄位複製憑證資訊。
  2. 必要的話,將 Base64 字串解碼為文字。
  3. 將憑證儲存至檔案。 (您可以使用所提供的名稱或您自己的檔名)。
  4. 提供驅動程式或用戶端的憑證路徑。

CLI 端點面板
CLI 端點面板

CLI 外掛程式支援服務專屬憑證

您可以使用指令 ibmcloud cdb deployment-cacert "your-service-name",使用 CLI 外掛程式來顯示部署的已解碼憑證。 它會將 base64 解碼成文字。 將指令的輸出複製並儲存至檔案,並提供檔案的驅動程式路徑。

其他驅動程式

MySQL 具有語言驅動程式的陣列。 下表涵蓋了幾種最常見的情況。 有關詳細信息,請參閱MySQL's連接器和 API。

MySQL驅動程式
語言 驅動程式 範例
PHP mysql 交易的 API 支援
Ruby ruby-mysql Ruby/MySQL API
C# ODBC LiMySQL連接器/ ODBC開發人員指南
進行 mysql Go-MySQL-Driver

使用 PHP 連接至 MySQL 時,必須將鑑別外掛程式從 sha256_password 變更為 mysql_native_password。