快速入門:在 適用於 PostgreSQL 的 Azure 資料庫 靈活伺服器中使用 Java 和 JDBC

本文說明如何建立一個範例應用程式,使用 Java 和 JDBC適用於 PostgreSQL 的 Azure 資料庫 中儲存及檢索資訊。

JDBC 是連接傳統關聯式資料庫的標準 Java API。

本文包含兩種認證方法:Microsoft Entra 認證與 PostgreSQL 認證。 [無密碼] 索引標籤會顯示 Microsoft Entra 驗證,而 [密碼] 索引標籤則會顯示 PostgreSQL 驗證。

Microsoft Entra 驗證是一種機制,會使用 Microsoft Entra ID 中所定義的身分識別以連線到適用於 PostgreSQL 的 Azure 資料庫。 透過使用 Microsoft Entra 認證,您可以集中管理資料庫使用者身份及其他 Microsoft 服務,簡化權限管理。

PostgreSQL 驗證會使用儲存在 PostgreSQL 中的帳戶。 如果你選擇用密碼作為帳號的憑證,請將這些憑證儲存在 user 資料表中。 因為這些密碼是儲存在 PostgreSQL 裡,你需要自己管理密碼的輪替。

先決條件

準備工作環境

首先,使用下列命令來設定一些環境變數。

export AZ_RESOURCE_GROUP=database-workshop
export AZ_DATABASE_SERVER_NAME=<YOUR_DATABASE_SERVER_NAME>
export AZ_DATABASE_NAME=<YOUR_DATABASE_NAME>
export AZ_LOCATION=<YOUR_AZURE_REGION>
export AZ_POSTGRESQL_AD_NON_ADMIN_USERNAME=<YOUR_POSTGRESQL_AD_NON_ADMIN_USERNAME>
export AZ_LOCAL_IP_ADDRESS=<YOUR_LOCAL_IP_ADDRESS>
export CURRENT_USERNAME=$(az ad signed-in-user show --query userPrincipalName -o tsv)

將預留位置取代為下列值,本文通篇都將使用這些值:

  • <YOUR_DATABASE_SERVER_NAME>: 你的 適用於 PostgreSQL 的 Azure 資料庫 靈活伺服器名稱,應該在 Azure 中是唯一的。
  • <YOUR_DATABASE_NAME>: 這是 適用於 PostgreSQL 的 Azure 資料庫 靈活伺服器的資料庫名稱,該伺服器在 Azure 內應該是唯一的。
  • <YOUR_AZURE_REGION>:要使用的 Azure 區域。 你可以預設使用 eastus ,但選擇離你居住地較近的地區。 您可輸入 az account list-locations 來查看可用區域的完整清單。
  • <YOUR_POSTGRESQL_AD_NON_ADMIN_USERNAME>: 你的 適用於 PostgreSQL 的 Azure 資料庫 彈性伺服器的用戶名。 請確認使用者名稱是你 Microsoft Entra 租戶中的有效使用者。
  • <YOUR_LOCAL_IP_ADDRESS>: 你本機電腦的 IP 位址,從它上執行 Spring Boot 應用程式。 找到它的一種便捷方法是打開 whatismyip.akamai.com

這很重要

設定 <YOUR_POSTGRESQL_AD_NON_ADMIN_USERNAME>時,該使用者必須已存在於你的 Microsoft Entra 租戶中,否則你無法在資料庫中建立 Microsoft Entra 使用者。

接下來,使用下列命令建立資源群組:

az group create \
    --name $AZ_RESOURCE_GROUP \
    --location $AZ_LOCATION \
    --output tsv

建立一個彈性伺服器

下列各節說明如何建立及設定資料庫執行個體。

建立一個彈性伺服器並設定管理員使用者

備註

欲了解更多關於建立 適用於 PostgreSQL 的 Azure 資料庫 彈性伺服器的詳細資訊,請參閱快速入門:建立 適用於 PostgreSQL 的 Azure 資料庫 彈性伺服器

如果您正在使用 Azure CLI,請執行下列命令來確定其具有足夠的權限:

az login --scope https://graph.microsoft.com/.default

執行下列命令來建立伺服器:

az postgres flexible-server create \
    --resource-group $AZ_RESOURCE_GROUP \
    --name $AZ_DATABASE_SERVER_NAME \
    --location $AZ_LOCATION \
    --yes \
    --output tsv

若要在建立伺服器之後設定 Microsoft Entra 系統管理員,請遵循在 適用於 PostgreSQL 的 Azure 資料庫中管理 Microsoft Entra 角色中的步驟。

這很重要

當你設定管理員時,你會新增一個擁有完整管理員權限的使用者到 適用於 PostgreSQL 的 Azure 資料庫 靈活伺服器的 Azure 資料庫。 你可以在 適用於 PostgreSQL 的 Azure 資料庫 彈性伺服器上建立多個 Microsoft Entra 管理員。

有任何問題嗎? 請告訴我們。

設定適用於 PostgreSQL 的 Azure 資料庫執行個體的防火牆規則

適用於 PostgreSQL 的 Azure 資料庫 的彈性伺服器預設是安全的。 他們有防火牆,會封鎖所有進來的連線。 要使用你的資料庫,可以新增防火牆規則,讓你的本地 IP 位址存取資料庫伺服器。

由於您已在本文開頭設定了本地 IP 位址,因此您可以執行下列命令來開啟伺服器的防火牆:

az postgres flexible-server firewall-rule create \
    --resource-group $AZ_RESOURCE_GROUP \
    --name $AZ_DATABASE_SERVER_NAME \
    --rule-name $AZ_DATABASE_SERVER_NAME-database-allow-local-ip \
    --start-ip-address $AZ_LOCAL_IP_ADDRESS \
    --end-ip-address $AZ_LOCAL_IP_ADDRESS \
    --output tsv

如果您是從 Windows 電腦上的 Windows 子系統 Linux 版 (WSL) 連線到 適用於 PostgreSQL 的 Azure 資料庫 彈性伺服器,則需要將 WSL 主機識別碼新增至防火牆。

透過 WSL 執行以下指令,取得你主機的 IP 位址:

cat /etc/resolv.conf

複製術語 nameserver後面的 IP 位址,然後使用以下指令設定 WSL IP 位址的環境變數:

AZ_WSL_IP_ADDRESS=<the-copied-IP-address>

然後,使用下列命令,將伺服器的防火牆開啟至 WSL 應用程式:

az postgres flexible-server firewall-rule create \
    --resource-group $AZ_RESOURCE_GROUP \
    --name $AZ_DATABASE_SERVER_NAME \
    --rule-name $AZ_DATABASE_SERVER_NAME-database-allow-local-ip \
    --start-ip-address $AZ_WSL_IP_ADDRESS \
    --end-ip-address $AZ_WSL_IP_ADDRESS \
    --output tsv

設定適用於 PostgreSQL 的 Azure 資料庫

使用下列指令建立新的資料庫:

az postgres flexible-server db create \
    --resource-group $AZ_RESOURCE_GROUP \
    --database-name $AZ_DATABASE_NAME \
    --server-name $AZ_DATABASE_SERVER_NAME \
    --output tsv

建立 Azure 資料庫適用於 PostgreSQL 的非系統管理員使用者並授予權限

接下來,建立非系統管理員使用者,並授與資料庫的所有權限。

備註

欲了解更多關於管理 適用於 PostgreSQL 的 Azure 資料庫 用戶的詳細資訊,請參閱 適用於 PostgreSQL 的 Azure 資料庫 中的「管理 Microsoft Entra 角色」。

建立一個名為 create_ad_user.sql 的 SQL 腳本,用來建立非管理員使用者。 新增下列內容,並將其儲存在本地:

cat << EOF > create_ad_user.sql
select * from pgaadauth_create_principal('$AZ_POSTGRESQL_AD_NON_ADMIN_USERNAME', false, false);
EOF

接著,使用以下指令執行 SQL 腳本並建立 Microsoft Entra 非管理員使用者:

psql "host=$AZ_DATABASE_SERVER_NAME.postgres.database.azure.com user=$CURRENT_USERNAME dbname=postgres port=5432 password=$(az account get-access-token --resource-type oss-rdbms --output tsv --query accessToken) sslmode=require" < create_ad_user.sql

請使用以下指令移除暫存的 SQL 腳本檔案:

rm create_ad_user.sql

建立新的 Java 專案

使用你喜愛的 IDE,使用 Java 8 或更新版本建立一個新的 Java 專案。 在根目錄中新增一個包含以下內容的 pom.xml 檔案:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.example</groupId>
    <artifactId>demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>demo</name>

    <properties>
        <java.version>1.8</java.version>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
    </properties>

    <dependencies>
      <dependency>
        <groupId>org.postgresql</groupId>
        <artifactId>postgresql</artifactId>
        <version>42.7.5</version>
      </dependency>
      <dependency>
        <groupId>com.azure</groupId>
        <artifactId>azure-identity-extensions</artifactId>
        <version>1.2.0</version>
      </dependency>
    </dependencies>
</project>

此檔案是可設定要使用之專案的 Apache Maven 檔案:

  • Java 8
  • 適用於 Java 的最新 PostgreSQL 驅動程式

準備組態檔以連線到適用於 PostgreSQL 的 Azure 資料庫

建立 一個 src/main/resources/application.properties 檔案,並新增以下內容:

cat << EOF > src/main/resources/application.properties
url=jdbc:postgresql://${AZ_DATABASE_SERVER_NAME}.postgres.database.azure.com:5432/${AZ_DATABASE_NAME}?sslmode=require&authenticationPluginClassName=com.azure.identity.extensions.jdbc.postgresql.AzurePostgresqlAuthenticationPlugin
user=${AZ_POSTGRESQL_AD_NON_ADMIN_USERNAME}
EOF

備註

配置內容 url 包括 ?sslmode=require 確保 JDBC 驅動程式在連接至資料庫時使用 TLS (傳輸層安全性)。 使用 TLS 是 適用於 PostgreSQL 的 Azure 資料庫 彈性伺服器的強制性操作,且是建議的安全措施。

建立 SQL 檔案以產生資料庫架構

使用 src/main/resources/schema.sql 檔案來建立資料庫結構。 建立該檔案,並新增以下內容:

DROP TABLE IF EXISTS todo;
CREATE TABLE todo (id SERIAL PRIMARY KEY, description VARCHAR(255), details VARCHAR(4096), done BOOLEAN);

撰寫應用程式程序代碼

以下章節將介紹如何撰寫連接資料庫、定義資料模型及執行基本 CRUD 操作的 Java 程式碼。

連結至資料庫

接著,加入使用 JDBC 來儲存和檢索 適用於 PostgreSQL 的 Azure 資料庫 彈性伺服器資料的 Java 程式碼。

建立 src/main/java/DemoApplication.java 檔案,並新增下列內容:

package com.example.demo;

import java.sql.*;
import java.util.*;
import java.util.logging.Logger;

public class DemoApplication {

    private static final Logger log;

    static {
        System.setProperty("java.util.logging.SimpleFormatter.format", "[%4$-7s] %5$s %n");
        log =Logger.getLogger(DemoApplication.class.getName());
    }

    public static void main(String[] args) throws Exception {
        log.info("Loading application properties");
        Properties properties = new Properties();
        properties.load(DemoApplication.class.getClassLoader().getResourceAsStream("application.properties"));

        log.info("Connecting to the database");
        Connection connection = DriverManager.getConnection(properties.getProperty("url"), properties);
        log.info("Database connection test: " + connection.getCatalog());

        log.info("Create database schema");
        Scanner scanner = new Scanner(DemoApplication.class.getClassLoader().getResourceAsStream("schema.sql"));
        Statement statement = connection.createStatement();
        while (scanner.hasNextLine()) {
            statement.execute(scanner.nextLine());
        }

        /*
        Todo todo = new Todo(1L, "configuration", "congratulations, you have set up JDBC correctly!", true);
        insertData(todo, connection);
        todo = readData(connection);
        todo.setDetails("congratulations, you have updated data!");
        updateData(todo, connection);
        deleteData(todo, connection);
        */

        log.info("Closing database connection");
        connection.close();
    }
}

有任何問題嗎? 請告訴我們。

這段Java程式碼利用 application.properties 和你之前建立的 schema.sql 檔案,連接到適用於 PostgreSQL 的 Azure 資料庫靈活的伺服器,建立儲存資料的結構。

在此檔案中,插入、讀取、更新和刪除資料的方法會註解出去。本文其餘部分會介紹這些方法的編碼,你可以依序取消註解。

備註

資料庫認證會儲存在 application.properties 檔案的 user 和 password 屬性中。 程式碼在執行 DriverManager.getConnection(properties.getProperty("url"), properties); 時會使用這些憑證,因為屬性檔會作為引數傳入。

您現在可以使用慣用的工具來執行此主要類別:

  • 你可以用你的 IDE 右鍵點擊 DemoApplication 類別並執行它。
  • 您可以使用 Maven 執行 mvn exec:java -Dexec.mainClass="com.example.demo.DemoApplication" 以執行應用程式。

應用程式會連接到 適用於 PostgreSQL 的 Azure 資料庫 彈性伺服器,建立資料庫結構,然後關閉連線,如你在主控台日誌中看到的:

[INFO   ] Loading application properties
[INFO   ] Connecting to the database
[INFO   ] Database connection test: demo
[INFO   ] Create database schema
[INFO   ] Closing database connection

建立領域類別

在該Todo類別旁邊建立一個新的 DemoApplication Java 類別,並加入以下程式碼:

package com.example.demo;

public class Todo {

    private Long id;
    private String description;
    private String details;
    private boolean done;

    public Todo() {
    }

    public Todo(Long id, String description, String details, boolean done) {
        this.id = id;
        this.description = description;
        this.details = details;
        this.done = done;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public String getDetails() {
        return details;
    }

    public void setDetails(String details) {
        this.details = details;
    }

    public boolean isDone() {
        return done;
    }

    public void setDone(boolean done) {
        this.done = done;
    }

    @Override
    public String toString() {
        return "Todo{" +
                "id=" + id +
                ", description='" + description + '\'' +
                ", details='" + details + '\'' +
                ", done=" + done +
                '}';
    }
}

這個類別是一個領域模型,映射到 todo 你執行 schema.sql 腳本時建立的資料表。

將資料插入適用於 PostgreSQL 的 Azure 資料庫

在 src/main/java/DemoApplication.jav 檔案中,在 main 方法後面新增下列方法,以將資料插入資料庫:

private static void insertData(Todo todo, Connection connection) throws SQLException {
    log.info("Insert data");
    PreparedStatement insertStatement = connection
            .prepareStatement("INSERT INTO todo (id, description, details, done) VALUES (?, ?, ?, ?);");

    insertStatement.setLong(1, todo.getId());
    insertStatement.setString(2, todo.getDescription());
    insertStatement.setString(3, todo.getDetails());
    insertStatement.setBoolean(4, todo.isDone());
    insertStatement.executeUpdate();
}

您現在可以取消 main 方法中下列兩行的註解:

Todo todo = new Todo(1L, "configuration", "congratulations, you have set up JDBC correctly!", true);
insertData(todo, connection);

當你執行主類別時,應該會產生以下輸出:

[INFO   ] Loading application properties
[INFO   ] Connecting to the database
[INFO   ] Database connection test: demo
[INFO   ] Create database schema
[INFO   ] Insert data
[INFO   ] Closing database connection

從 適用於 PostgreSQL 的 Azure 資料庫 讀取資料

為了驗證你的程式碼是否正確運作,請閱讀你之前插入的資料。

在 src/main/java/DemoApplication.java 檔案中的 insertData 方法後面新增下列方法,以讀取資料庫中的資料:

private static Todo readData(Connection connection) throws SQLException {
    log.info("Read data");
    PreparedStatement readStatement = connection.prepareStatement("SELECT * FROM todo;");
    ResultSet resultSet = readStatement.executeQuery();
    if (!resultSet.next()) {
        log.info("There is no data in the database!");
        return null;
    }
    Todo todo = new Todo();
    todo.setId(resultSet.getLong("id"));
    todo.setDescription(resultSet.getString("description"));
    todo.setDetails(resultSet.getString("details"));
    todo.setDone(resultSet.getBoolean("done"));
    log.info("Data read from the database: " + todo.toString());
    return todo;
}

您現在可以取消 main 方法中下列行的註解:

todo = readData(connection);

當你執行主類別時,應該會產生以下輸出:

[INFO   ] Loading application properties
[INFO   ] Connecting to the database
[INFO   ] Database connection test: demo
[INFO   ] Create database schema
[INFO   ] Insert data
[INFO   ] Read data
[INFO   ] Data read from the database: Todo{id=1, description='configuration', details='congratulations, you have set up JDBC correctly!', done=true}
[INFO   ] Closing database connection

更新 適用於 PostgreSQL 的 Azure 資料庫 中的資料

要更新資料,請使用以下步驟。

在 src/main/java/DemoApplication.java 檔案中的 readData 方法後面新增下列方法,以更新資料庫中的資料:

private static void updateData(Todo todo, Connection connection) throws SQLException {
    log.info("Update data");
    PreparedStatement updateStatement = connection
            .prepareStatement("UPDATE todo SET description = ?, details = ?, done = ? WHERE id = ?;");

    updateStatement.setString(1, todo.getDescription());
    updateStatement.setString(2, todo.getDetails());
    updateStatement.setBoolean(3, todo.isDone());
    updateStatement.setLong(4, todo.getId());
    updateStatement.executeUpdate();
    readData(connection);
}

您現在可以取消 main 方法中下列兩行的註解:

todo.setDetails("congratulations, you have updated data!");
updateData(todo, connection);

當你執行主類別時,應該會產生以下輸出:

[INFO   ] Loading application properties
[INFO   ] Connecting to the database
[INFO   ] Database connection test: demo
[INFO   ] Create database schema
[INFO   ] Insert data
[INFO   ] Read data
[INFO   ] Data read from the database: Todo{id=1, description='configuration', details='congratulations, you have set up JDBC correctly!', done=true}
[INFO   ] Update data
[INFO   ] Read data
[INFO   ] Data read from the database: Todo{id=1, description='configuration', details='congratulations, you have updated data!', done=true}
[INFO   ] Closing database connection

刪除 適用於 PostgreSQL 的 Azure 資料庫 中的資料

最後,刪除您先前插入的資料。

在 src/main/java/DemoApplication.java 檔案中的 updateData 方法後面新增下列方法,以刪除資料庫中的資料:

private static void deleteData(Todo todo, Connection connection) throws SQLException {
    log.info("Delete data");
    PreparedStatement deleteStatement = connection.prepareStatement("DELETE FROM todo WHERE id = ?;");
    deleteStatement.setLong(1, todo.getId());
    deleteStatement.executeUpdate();
    readData(connection);
}

您現在可以取消 main 方法中下列行的註解:

deleteData(todo, connection);

當你執行主類別時,應該會產生以下輸出:

[INFO   ] Loading application properties
[INFO   ] Connecting to the database
[INFO   ] Database connection test: demo
[INFO   ] Create database schema
[INFO   ] Insert data
[INFO   ] Read data
[INFO   ] Data read from the database: Todo{id=1, description='configuration', details='congratulations, you have set up JDBC correctly!', done=true}
[INFO   ] Update data
[INFO   ] Read data
[INFO   ] Data read from the database: Todo{id=1, description='configuration', details='congratulations, you have updated data!', done=true}
[INFO   ] Delete data
[INFO   ] Read data
[INFO   ] There is no data in the database!
[INFO   ] Closing database connection

清理資源

你創建了一個使用 JDBC 來儲存和檢索 適用於 PostgreSQL 的 Azure 資料庫 靈活伺服器資料的 Java 應用程式。

若要清除本快速入門期間使用的所有資源,請使用下列命令刪除資源群組:

az group delete \
    --name $AZ_RESOURCE_GROUP \
    --yes