IBM Cloud Docs
连接外部应用程序

连接外部应用程序

应用程序和驱动程序使用连接字符串来建立与 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... 结合了方案、验证、主机和路径的 URI。
Certificate Name 数据库部署服务专有证书的分配名称。
Certificate Base64 证书的 base64 编码版本。
  • 0... 指示数组中的一个或多个条目。

当给定在连接信息的“组合”字段中找到 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 证书常见问题

使用服务专有证书

  1. 端点 面板或连接信息的 Base64 字段复制证书信息。
  2. 如果需要,将 Base64 字符串解码为文本。
  3. 将证书保存到文件中。 (可以使用提供的名称或您自己的文件名)。
  4. 向驱动程序或客户机提供证书的路径。

CLI 端点面板
CLI 端点面板* CLI 端点

CLI 插件支持服务专有证书

您可以使用命令 ibmcloud cdb deployment-cacert "your-service-name" 通过 CLI 插件显示用于部署的解码证书。 它将 base64 解码为文本。 复制命令的输出并将其保存到文件中,然后提供该文件的驱动程序路径。

其他驱动程序

MySQL 具有一组语言驱动程序。 下表介绍了几种最常见的情况。 有关详细信息,请查阅MySQL's 连接器和 API

MySQL驱动程序
语言 驱动程序 示例
PHP mysql 对事务的 API 支持
Ruby ruby-mysql Ruby/MySQLAPI
C# ODBC LiMySQL连接器/ODBC开发人员指南
执行 mysql Go-MySQL-Driver

使用 PHP 连接到 MySQL 时,需要将认证插件从 sha256_password 更改为 mysql_native_password