首页 > 解决方案 > 如何连接到local.settings.json的JDBC连接字符串?

问题描述

我想通过基于 Java 的 Azure Functions 写入 SQL 数据库。

我在 local.settings.json 中有 JDBC 的 SQLconnstring。如何从设置文件而不是硬编码到 java 文件中正确获取此连接?

package com.function;
import com.microsoft.azure.functions.annotation.*;
import com.microsoft.azure.functions.*;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
/**
 * Azure Functions with Azure Storage Queue trigger.
 */
public class TopicTriggerSQLOutput {
    /**
     * This function will be invoked when a new message is received at the specified path. The 
message contents are provided as input to this function.
     */
    @FunctionName("TopicTriggerSQLOutput")
    public void run(
        @ServiceBusTopicTrigger(
            name = "message",
            topicName = "newtopic",
            subscriptionName = "newsubscription",
            connection = "topicconnstring"
        ) String message,
       final ExecutionContext context
    ) {
        /*Creating SQL Connection. I need help here:
        */

            /*How to get connection string from local.settings.json instead of hard coding?*/
            String connectionUrl =
                    "jdbc:sqlserver://yourserver.database.windows.net:1433;"
                            + "database=AdventureWorks;"
                            + "user=yourusername@yourserver;"
                            + "password=yourpassword;"
                            + "encrypt=true;"
                            + "trustServerCertificate=false;"
                            + "loginTimeout=30;";

            try (Connection connection = DriverManager.getConnection(connectionUrl);) {
                // SQL Code here.
            }
            // Handle any errors that may have occurred.
            catch (SQLException e) {
                e.printStackTrace();
            }

        //context.getLogger().info(message);
    }
}

标签: javaazure-functions

解决方案


您可以使用System.getenv("")local.settings.json文件中获取值。例如,我们可以使用String connectionUrl =System.getenv("SQLConnectionString");获取local.settings.json文件中的sql连接字符串。

在此处输入图像描述


推荐阅读