IBM Cloud Docs
将外部应用程序连接到 PostgreSQL 部署

将外部应用程序连接到 PostgreSQL 部署

应用程序和驱动程序使用连接字符串来建立与 IBM Cloud® Databases for PostgreSQL的连接。 该服务专门为驱动程序和应用程序提供连接字符串。 连接字符串将显示在部署的“概述”的“端点”面板中,并且还可以从 Cloud Databases CLI 插件Cloud Databases API 中检索。

连接字符串可以由您在部署上创建的任何凭证使用。 虽然您可以将管理用户用于所有连接和应用程序,但最好专门为要连接的应用程序创建用户。 有关详细信息,请参阅 获取连接字符串

使用语言的驱动程序连接到 PostgreSQL 部署

驱动程序与部署建立连接所需的所有信息都在连接字符串的 "postgres" 部分中。 该表包含供参考的细目。

postgres/URI 连接信息
字段名称 索引 描述
Type 连接类型 - PostgreSQL, 为 "URI"。
Scheme URI 的方案 - PostgreSQL, 是 "postgresql"。
Path URI 的路径 - 对于 PostgreSQL, 是数据库名称。 默认值为 ibmclouddb
Authentication Username 用于连接的用户名。
Authentication Password 用户的密码-可能显示为 $PASSWORD
Authentication Method 如何进行认证;“直接”认证由驱动程序处理。
Hosts 0... 要连接的主机名和端口。
Composed 0... 结合了方案、验证、主机和路径的 URI。
Certificate Name 数据库部署服务专有证书的分配名称。
Certificate Base64 证书的 base64 编码版本。
  • 0... 指示数组中可能有一个或多个这些条目。

当给定在连接信息的“组合”字段中找到 URI 格式的连接字符串时,许多 PostgreSQL 驱动程序能够与您的部署建立连接。 例如

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

以下示例使用连接字符串和 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;
import java.util.logging.*;

public class PGConnect {

    private final static Logger LOGGER = Logger.getLogger(Logger.GLOBAL_LOGGER_NAME);

    private Connection connect() {

        final String url = "jdbc:postgresql://host:port/ibmclouddb";

        Properties props = new Properties();
        props.setProperty("user","admin");
        props.setProperty("password","mypassword123");
        props.setProperty("ssl","true");
        props.setProperty("sslmode","verify-full");
        props.setProperty("sslrootcert", "/path/to/cert");

        Connection conn = null;
        while (conn == null) {
            try {
                conn = DriverManager.getConnection(url, props);
                System.out.println("Connected to PG");
            } catch (SQLException e) {
                System.out.printf("%s\n", e);
                LOGGER.info("Not connected, retying ...");
            }
        }

        return conn;

    }

    public static void main(String[] args) {

        PGConnect icd = new PGConnect();

        try {
            Connection connection = icd.connect();
            Statement stmt = connection.createStatement();

            ResultSet rs = stmt.executeQuery("SELECT * from pg_database");
            while (rs.next()) {
                System.out.println("DB Name: " + rs.getString(1));
            }

        } catch (SQLException e) {
            System.out.println(e.getMessage());
        }   
    }
}

以下示例使用来自连接字符串和 Python 驱动程序 Psycopg2 的信息来连接到数据库。 这只是一个简单的连接示例,没有错误处理或重试逻辑,可能不适合生产。

import psycopg2

try:
    conn = psycopg2.connect(
      host="hostname.databases.appdomain.cloud",
      port= 31525,
      user="username",
      password="password",
      sslmode="verify-full",
      sslrootcert="/path/to/cert/ca-certificate.crt",
      database="ibmclouddb")
except:
    print("Unable to connect to database")

cur = conn.cursor()
cur.execute("SELECT datname FROM pg_database")
rows = cur.fetchall()

print("List of databases:")
for row in rows:
    print("  ",row[0])

以下示例使用连接字符串和 Node 驱动程序 node-postgres 中的信息来连接到数据库。

const pg = require("pg");
const fs = require("fs");

let connectionString = "postgres://<username>:<password>@<host>:<port>/<database>";
let caCert = fs.readFileSync('/path/to/cert');

// set up a client with your PostgreSQL connection string and TLS options
let client = new pg.Client({
    connectionString: connectionString,
    ssl: {
    ca: caCert,
    rejectUnauthorized: true
    }
});


client.connect(function(err) {
    if (err) {
        console.log(err);
        process.exit(1);
    } else {
        // query for the names of the databases
        client.query(
            "SELECT datname FROM pg_database;",
            function(err, result) {
                if (err) {
                    console.log(err);
                }
                // return the names of the databases
                console.log(result.rows);
                client.end();
            }
        );
    }
});

要使用 node-postgres driver,请从部署的连接字符串中除去 sslmode 参数。 否则,此参数将覆盖 ssl: {...} 参数,从而阻止 CA 证书正确装入。

驱动程序 TLS 和服务专有证书支持

与 Databases for PostgreSQL 的所有连接都已启用 TLS 1.2,因此用于连接的驱动程序需要能够支持加密。 您的部署还附带了服务专有证书,这样驱动程序就能在连接时验证服务器。

有关更多信息,请参阅 Cloud Databases 证书常见问题

使用服务专有证书

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

CLI 端点面板
CLI 插件信息选项卡

CLI 插件支持服务专有证书

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

其他驱动程序

PostgreSQL 有大量的语言驱动程序。 此表涵盖一些最常见的驱动程序。

PostgreSQL驱动程序
语言 驱动程序 示例
PHP pgsql 链接
Ruby ruby-pg 链接
Ruby on Rails Rails 链接
C# ODBC 链接
执行 pq 链接
Node node-postgres 链接