你当前正在访问 Microsoft Azure Global Edition 技术文档网站。 如果需要访问由世纪互联运营的 Microsoft Azure 中国技术文档网站,请访问 https://docs.azure.cn。

快速入门:将 Java 和 JDBC 用于 Azure HorizonDB

本文演示如何创建一个示例应用程序,该应用程序使用 Java 和 JDBC 在 Azure HorizonDB 中存储和检索信息。

JDBC 是连接到传统关系数据库的标准Java API。

使用 2026-10-01 预览版 REST API 预配群集、密码身份验证、计算池和防火墙规则。 Microsoft Entra 对这些管理请求进行身份验证。 Java 应用程序使用 PostgreSQL 用户名和密码身份验证,而不是管理访问令牌。

PostgreSQL 身份验证使用 PostgreSQL 中存储的帐户,需要自行管理密码轮换。

先决条件

准备工作环境

在同一交互式 Bash 会话中运行本文中的命令。 如果命令失败,请更正错误,并在继续之前重试该步骤。 此设置会禁用 Bash errexit 选项,因此失败的请求不会终止你的会话。

设置以下环境变量,将带引号的占位符替换为你自己的值:

set +e
set -uo pipefail

export AZ_SUBSCRIPTION_ID="<YOUR_SUBSCRIPTION_ID>"
export AZ_TENANT_ID="<YOUR_TENANT_ID>"
export AZ_CLIENT_ID="<YOUR_APP_CLIENT_ID>"
export AZ_RESOURCE_GROUP=database-workshop
export AZ_DATABASE_CLUSTER_NAME="<YOUR_DATABASE_CLUSTER_NAME>"
export AZ_POOL_NAME="${AZ_DATABASE_CLUSTER_NAME}-pool"
export AZ_DATABASE_NAME=demo
export AZ_LOCATION="<YOUR_AZURE_REGION>"
export AZ_POSTGRESQL_ADMIN_USERNAME=demo
export AZ_POSTGRESQL_NON_ADMIN_USERNAME=demo-non-admin
export AZ_LOCAL_IP_ADDRESS="<YOUR_PUBLIC_IPV4_ADDRESS>"
export AZ_HORIZONDB_API_VERSION=2026-10-01-preview

read -r -s -p "PostgreSQL administrator password: " AZ_POSTGRESQL_ADMIN_PASSWORD
printf '\n'
export AZ_POSTGRESQL_ADMIN_PASSWORD
read -r -s -p "PostgreSQL nonadmin password: " AZ_POSTGRESQL_NON_ADMIN_PASSWORD
printf '\n'
export AZ_POSTGRESQL_NON_ADMIN_PASSWORD

export AZ_RESOURCE_GROUP_URL="https://management.azure.com/subscriptions/${AZ_SUBSCRIPTION_ID}/resourceGroups/${AZ_RESOURCE_GROUP}"
export AZ_CLUSTER_URL="${AZ_RESOURCE_GROUP_URL}/providers/Microsoft.HorizonDb/clusters/${AZ_DATABASE_CLUSTER_NAME}"
export AZ_POOL_URL="${AZ_CLUSTER_URL}/pools/${AZ_POOL_NAME}"

使用以下值替换占位符,在本文中将使用这些值:

  • <YOUR_SUBSCRIPTION_ID>:Azure订阅 ID。
  • <YOUR_TENANT_ID> 和 <YOUR_APP_CLIENT_ID>:应用注册中的目录(租户)ID 和应用程序(客户端)ID。
  • <YOUR_DATABASE_CLUSTER_NAME>:订阅和资源组中唯一的群集名称。 使用 1-58 个小写字母、数字或连字符,以字母或数字开头和结尾。 派生池名称添加 -pool 后缀,并且必须与群集名称不同。
  • <YOUR_AZURE_REGION>:支持 HorizonDB 的区域以及下一部分使用的计算配置。 此示例使用具有 2 个 vCore 的 AMD 第 1 代;选择受支持的区域或调整这些池设置。
  • <YOUR_PUBLIC_IPV4_ADDRESS>:运行 Java 应用程序的环境所使用的公共出站 IPv4 地址。 专用地址或 DNS 服务器地址不是有效的替代地址。

PostgreSQL 密码必须包含 8-128 个字符,并满足服务的密码要求。 使用大写字母、小写字母、数字和非字母数字的组合。 不要将机密信息纳入源代码管理,也不要对这些命令启用 shell 跟踪。

获取 ARM 访问令牌

使用Microsoft 标识平台 客户端凭据流请求 Azure 资源管理器 的令牌。 此函数会提示输入应用的客户端密钥而不显示它,并且不打印返回的令牌:

get_arm_access_token() {
    local client_secret token_response access_token
    unset AZ_ARM_ACCESS_TOKEN
    if ! read -r -s -p "Microsoft Entra app client secret: " client_secret; then
        printf 'Unable to read the client secret.\n' >&2
        return 1
    fi
    printf '\n'
    if ! token_response=$(
        printf '%s' "$client_secret" |
        curl --fail-with-body --silent --show-error \
            --request POST \
            "https://login.microsoftonline.com/${AZ_TENANT_ID}/oauth2/v2.0/token" \
            --header "Content-Type: application/x-www-form-urlencoded" \
            --data-urlencode "client_id=${AZ_CLIENT_ID}" \
            --data-urlencode "client_secret@-" \
            --data-urlencode "scope=https://management.azure.com/.default" \
            --data-urlencode "grant_type=client_credentials"
    ); then
        unset client_secret
        printf 'Access-token request failed.\n' >&2
        return 1
    fi
    unset client_secret
    if ! access_token=$(printf '%s' "$token_response" |
        jq -er '.access_token | select(type == "string" and length > 0)'); then
        printf 'The token response is missing a valid access token.\n' >&2
        return 1
    fi
    export AZ_ARM_ACCESS_TOKEN="$access_token"
}

get_arm_access_token

访问令牌会过期。 如果管理请求返回 HTTP 401,请在函数成功后再次运行 get_arm_access_token 并重试请求。 失败的请求返回错误而不关闭此 Bash 会话。

发送 REST 请求并等待完成

HorizonDB 预配操作是异步的。 在预配请求之前运行此帮助程序。 它遵循 Azure-AsyncOperation 或 Location 响应头,遵循 Retry-After,并在操作失败或状态异常时返回错误。 为此 Azure-AsyncOperation,它会读取 JSON status 字段。 对于 Location,HTTP 202 表示操作处于挂起状态,HTTP 200 或 204 表示操作已完成。 有关详细信息,请参阅跟踪异步Azure操作。

arm_request() {
    local method="$1" url="$2" work_dir code poll_url poll_type delay state
    local result=0 finished=0 attempt
    local -a args
    if ! work_dir=$(mktemp -d); then
        printf 'Unable to create the REST response directory.\n' >&2
        return 1
    fi
    args=(--fail-with-body --silent --show-error --request "$method"
        --header "Authorization: Bearer ${AZ_ARM_ACCESS_TOKEN}"
        --header "Content-Type: application/json"
        --dump-header "$work_dir/headers" --output "$work_dir/body"
        --write-out '%{http_code}')
    if [ "$method" = PUT ]; then
        args+=(--data-binary @-)
    fi
    if ! code=$(curl "${args[@]}" "$url"); then
        printf 'REST request failed (HTTP %s).\n' "$code" >&2
        if [ -f "$work_dir/body" ]; then cat "$work_dir/body" >&2; fi
        rm -f "$work_dir/headers" "$work_dir/body"
        rmdir "$work_dir"
        return 1
    fi
    poll_type=async
    poll_url=$(awk 'tolower($1) == "azure-asyncoperation:" {gsub("\r", "", $2); value=$2} END {print value}' "$work_dir/headers")
    if [ -z "$poll_url" ]; then
        poll_type=location
        poll_url=$(awk 'tolower($1) == "location:" {gsub("\r", "", $2); value=$2} END {print value}' "$work_dir/headers")
    fi
    if [ -n "$poll_url" ]; then
        case "$poll_url" in
            https://management.azure.com/*) ;;
            *) printf 'Unexpected operation-status URL; refusing to send the token.\n' >&2; result=1 ;;
        esac
        for ((attempt=1; result==0 && attempt<=120; attempt++)); do
            delay=$(awk 'tolower($1) == "retry-after:" {gsub("\r", "", $2); value=$2} END {print (value == "" ? 10 : value)}' "$work_dir/headers")
            case "$delay" in
                ''|*[!0-9]*) printf 'Invalid Retry-After header.\n' >&2; result=1; finished=1; break ;;
            esac
            sleep "$delay"
            if ! code=$(curl --fail-with-body --silent --show-error \
                --header "Authorization: Bearer ${AZ_ARM_ACCESS_TOKEN}" \
                --dump-header "$work_dir/headers" --output "$work_dir/body" \
                --write-out '%{http_code}' "$poll_url"); then
                cat "$work_dir/body" >&2
                result=1; finished=1; break
            fi
            if [ "$poll_type" = location ]; then
                case "$code" in
                    202) continue ;;
                    200|204) finished=1; break ;;
                    *) printf 'Unexpected operation-status HTTP code: %s\n' "$code" >&2
                       result=1; finished=1; break ;;
                esac
            fi
            if ! state=$(jq -er '.status | select(type == "string")' "$work_dir/body"); then
                printf 'Missing operation status.\n' >&2
                result=1; finished=1; break
            fi
            case "$state" in
                Succeeded) finished=1; break ;;
                Failed|Canceled) jq '{status, error}' "$work_dir/body" >&2; result=1; finished=1; break ;;
                Accepted|Running|InProgress|Provisioning|Updating) ;;
                *) printf 'Unexpected operation status: %s\n' "$state" >&2; result=1; finished=1; break ;;
            esac
        done
        if [ "$finished" -eq 0 ] && [ "$result" -eq 0 ]; then
            printf 'Operation did not finish within 120 polling attempts.\n' >&2
            result=1
        fi
    else
        case "$code" in
            200|201|204) ;;
            *) printf 'Missing operation-status URL for HTTP %s.\n' "$code" >&2; result=1 ;;
        esac
        if [ "$result" -eq 0 ] && [ -s "$work_dir/body" ]; then
            if ! jq -e . "$work_dir/body" >/dev/null; then
                printf 'Invalid JSON response.\n' >&2; result=1
            elif jq -e '.properties.provisioningState != null and .properties.provisioningState != "Succeeded"' "$work_dir/body" >/dev/null; then
                printf 'Resource is still provisioning but no operation-status URL was returned.\n' >&2; result=1
            fi
        fi
    fi
    rm -f "$work_dir/headers" "$work_dir/body"
    rmdir "$work_dir"
    if [ "$result" -eq 0 ]; then printf '%s request completed.\n' "$method"; fi
    return "$result"
}

创建资源组

如果已有目标资源组,请跳过此步骤。 否则,请使用 资源组 REST API。

jq -n '{location: env.AZ_LOCATION}' |
    arm_request PUT "${AZ_RESOURCE_GROUP_URL}?api-version=2021-04-01"

创建 Azure HorizonDB 群集

注释

资源名称(例如表名、数据库名)和资源标签中不得包含任何个人、敏感或机密信息。 你在这些字段中输入的数据不被视为客户数据。

以下部分使用与创建 Azure HorizonDB 群集相同的资源布局:PostgreSQL 17 群集、密码身份验证、一个预配的计算节点和一个池范围的防火墙规则。 每个 arm_request 都会等待各自的操作完成,然后再继续。

创建 Azure HorizonDB 群集

创建具有公用网络访问权限的群集,以及默认的七天备份保留期:

jq -n '{
    location: env.AZ_LOCATION,
    properties: {
        postgreSqlVersion: "17",
        network: {publicAccess: "Enabled"},
        backup: {geoRedundancy: "Disabled"}
    }
}' | arm_request PUT "${AZ_CLUSTER_URL}?api-version=${AZ_HORIZONDB_API_VERSION}"

群集资源不配置凭据或分配计算。 在以下步骤中创建这些资源。

遇到问题? 请告知我们。

启用 PostgreSQL 密码身份验证

配置服务创建的passwordMethod身份验证资源。 jq从环境中读取密码并将其转义为 JSON,而无需编写密码文件:

jq -n '{
    properties: {
        state: "Enabled",
        administratorLogin: env.AZ_POSTGRESQL_ADMIN_USERNAME,
        administratorLoginPassword: env.AZ_POSTGRESQL_ADMIN_PASSWORD
    }
}' | arm_request PUT "${AZ_CLUSTER_URL}/authentications/passwordMethod?api-version=${AZ_HORIZONDB_API_VERSION}"

创建计算池

创建一个禁用高可用性的 2 vCore AMD 第 1 代节点。 该服务自动将第一个池指定为读写池,并应用 PostgreSQL 17 的默认参数组:

jq -n '{
    properties: {
        computeModel: {
            type: "Provisioned",
            computeProcessor: "AMD",
            computeGeneration: 1,
            vCores: 2
        },
        nodeCount: 1,
        highAvailability: {mode: "Disabled"}
    }
}' | arm_request PUT "${AZ_POOL_URL}?api-version=${AZ_HORIZONDB_API_VERSION}"

对于生产可用性,请配置至少两个节点,并选择受支持的高可用性模式。

为 Azure HorizonDB 实例配置防火墙规则

公共网络访问不允许任意客户端连接。 在池上创建具有相同开始和结束地址的防火墙规则,以便它仅允许客户端 IPv4 地址:

jq -n '{
    properties: {
        startIpAddress: env.AZ_LOCAL_IP_ADDRESS,
        endIpAddress: env.AZ_LOCAL_IP_ADDRESS
    }
}' | arm_request PUT "${AZ_POOL_URL}/firewallRules/client-ip?api-version=${AZ_HORIZONDB_API_VERSION}"

如果使用 WSL,则允许 WSL 使用的公共出站 IPv4 地址。 请勿使用来自 nameserver 的/etc/resolv.conf专用地址。

获取读写终结点

读取集群作用域的端点,其资源名称为集群名称:

get_read_write_endpoint() {
    local endpoint_response fqdn
    unset AZ_HORIZONDB_FQDN
    if ! endpoint_response=$(curl --fail-with-body --silent --show-error \
        --header "Authorization: Bearer ${AZ_ARM_ACCESS_TOKEN}" \
        "${AZ_CLUSTER_URL}/endpoints/${AZ_DATABASE_CLUSTER_NAME}?api-version=${AZ_HORIZONDB_API_VERSION}"); then
        printf 'Endpoint request failed.\n' >&2
        return 1
    fi
    if ! fqdn=$(printf '%s' "$endpoint_response" |
        jq -er '.properties.fullyQualifiedDomainName | select(type == "string" and length > 0)'); then
        printf 'The endpoint response is missing a valid hostname.\n' >&2
        return 1
    fi
    export AZ_HORIZONDB_FQDN="$fqdn"
}

get_read_write_endpoint

将此读写终结点用于 JDBC 应用程序。 单节点池没有符合条件的只读节点,因此其池范围的只读终结点不适用于此示例。

创建 Azure HorizonDB 数据库

创建一个名为create_database.sql创建应用程序数据库的 SQL 脚本:

cat <<'EOF' > create_database.sql
\getenv database_name AZ_DATABASE_NAME
CREATE DATABASE :"database_name";
EOF

连接到现有 postgres 数据库以创建应用程序数据库。 ON_ERROR_STOP 会在 SQL 语句失败时停止脚本:

PGPASSWORD="$AZ_POSTGRESQL_ADMIN_PASSWORD" psql \
    "host=$AZ_HORIZONDB_FQDN user=$AZ_POSTGRESQL_ADMIN_USERNAME dbname=postgres port=5432 sslmode=require" \
    --no-psqlrc --set=ON_ERROR_STOP=1 --file=create_database.sql

现在,运行以下命令以删除临时 SQL 脚本文件:

rm create_database.sql

创建 Azure HorizonDB 非admin 用户并授予权限

为应用程序创建 PostgreSQL 非admin 角色。 授予数据库特权和权限,以在 public 架构中使用和创建对象。

创建名为create_user.sql的 SQL 脚本。 psql 从环境变量中读取角色名称和密码,并将其作为 SQL 标识符或字面量加引号:

cat <<'EOF' > create_user.sql
\getenv database_name AZ_DATABASE_NAME
\getenv role_name AZ_POSTGRESQL_NON_ADMIN_USERNAME
\getenv role_password AZ_POSTGRESQL_NON_ADMIN_PASSWORD
CREATE ROLE :"role_name" WITH LOGIN PASSWORD :'role_password';
GRANT ALL PRIVILEGES ON DATABASE :"database_name" TO :"role_name";
GRANT USAGE, CREATE ON SCHEMA public TO :"role_name";
EOF

在应用程序数据库中运行脚本:

PGPASSWORD="$AZ_POSTGRESQL_ADMIN_PASSWORD" psql \
    "host=$AZ_HORIZONDB_FQDN user=$AZ_POSTGRESQL_ADMIN_USERNAME dbname=$AZ_DATABASE_NAME port=5432 sslmode=require" \
    --no-psqlrc --set=ON_ERROR_STOP=1 --file=create_user.sql

现在,运行以下命令以删除临时 SQL 脚本文件:

rm create_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.3.6</version>
      </dependency>
    </dependencies>
</project>

此文件是一个 Apache Maven 文件,用于配置要使用的项目:

  • Java 8
  • PostgreSQL JDBC 驱动程序

准备配置文件以连接到 Azure HorizonDB

使用 JDBC URL 创建 src/main/resources/application.properties 。 应用程序从环境变量读取用户名和密码:

mkdir -p src/main/resources
cat << EOF > src/main/resources/application.properties
url=jdbc:postgresql://${AZ_HORIZONDB_FQDN}:5432/${AZ_DATABASE_NAME}?sslmode=require
EOF

注释

配置属性 url 包括 ?sslmode=require 确保在连接到数据库时 JDBC 驱动程序使用 TLS(传输层安全性)。 Azure HorizonDB 需要 TLS,这是建议的安全做法。

创建 SQL 文件以生成数据库架构

使用 src/main/resources/schema.sql 文件创建数据库架构。 使用以下内容创建该文件:

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

对应用程序进行编码

连接到数据库

接下来,添加使用 JDBC 从 Azure HorizonDB 实例存储和检索数据的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"));
        properties.setProperty("user", requiredEnvironmentVariable("AZ_POSTGRESQL_NON_ADMIN_USERNAME"));
        properties.setProperty("password", requiredEnvironmentVariable("AZ_POSTGRESQL_NON_ADMIN_PASSWORD"));

        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();
    }

    private static String requiredEnvironmentVariable(String name) {
        String value = System.getenv(name);
        if (value == null || value.isEmpty()) {
            throw new IllegalStateException("Set the environment variable " + name + " before running the application.");
        }
        return value;
    }
}

遇到问题? 请告知我们。

此Java代码使用 application.properties 和之前创建的 schema.sql 文件连接到 Azure HorizonDB 实例并创建存储数据的架构。

在此文件中,你可以看到我们将用于插入、读取、更新和删除数据的方法注释掉了:我们将在本文的其余部分编写这些方法,你也将能够依次取消对它们的注释。

应用程序将环境中的数据库用户名和密码添加到传递给 DriverManager.getConnection 的 Properties 中。 密码未存储在 application.properties. 如果从 IDE 运行应用程序,请在其运行配置中配置相同的环境变量。 当你从前面使用的 Bash 会话中运行 Maven 时,它会继承这些变量。

现在可以通过喜欢的工具执行此主类:

  • 使用 IDE 时,应该能够右键单击 DemoApplication 类并执行它。
  • 使用 Maven,可以通过执行以下操作来运行应用程序:mvn exec:java -Dexec.mainClass="com.example.demo.DemoApplication"。

应用程序应连接到 Azure HorizonDB 实例,创建数据库架构,然后关闭连接,如控制台日志中所示:

[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 脚本时创建的 表上映射的域模型。

将数据插入到 Azure HorizonDB 中

在 src/main/java/DemoApplication.java 文件中,在 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

从 Azure HorizonDB 读取数据

接下来,请阅读前面插入的数据,验证代码是否正常工作。

在 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

更新 Azure HorizonDB 中的数据

让我们更新之前插入的数据。

在 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

删除 Azure HorizonDB 中的数据

最后,让我们删除之前插入的数据。

仍在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

清理资源

祝贺! 你已创建一个Java应用程序,该应用程序使用 JDBC 从 Azure HorizonDB 实例存储和检索数据。

使用资源组 REST API 删除专用资源组。 如有必要,请获取新的访问令牌:

Warning

删除资源组会永久删除群集、其数据以及该组中的所有其他资源。 仅对专用快速入门资源组使用此命令。

get_arm_access_token
arm_request DELETE "${AZ_RESOURCE_GROUP_URL}?api-version=2021-04-01"