java - 如何从用 Java 编写的 Azure Function App 连接到 PostgreSQL?

标签 java postgresql azure jdbc azure-functions

我有一个 Azure 函数应用程序,其中有一个用 Java 编写的计时器触发器函数。我需要连接到部署在其中一台 Azure VM 上的 PostgreSQL(此处不使用托管 Postgres)。

我的代码:

import java.sql.*;

public class MyFunction {

    public static final String DB_URL              = "jdbc:postgresql://<host>:<port>/<dbName>";
    public static final String DB_USER             = "<dbUser>";
    public static final String DB_PASSWORD         = "<dbPassword>";

    @FunctionName("timerTrigger")
    public void timerTrigger(@TimerTrigger(name = "timerTriggerFunc", schedule = "0 */30 * * * *")
                                         String timerInfo, ExecutionContext context) {

        Connection connection = DriverManager.getConnection(DB_URL, DB_USER, DB_PASSWORD);
        connection.setAutoCommit(false);
    }
}

当我运行这个函数时,它抛出以下异常:

[11/29/2019 10:42:24] java.sql.SQLException: No suitable driver found for jdbc:postgresql://<host>:<port>/<dbName>
[11/29/2019 10:42:24]   at java.sql.DriverManager.getConnection(DriverManager.java:689)
[11/29/2019 10:42:24]   at java.sql.DriverManager.getConnection(DriverManager.java:247)

请帮忙解决这个问题。我在堆栈溢出中浏览了其他问题并进行了浏览,但没有在其他地方找到我的用例。

最佳答案

尝试导入 postgresql 驱动程序。我使用下面的代码成功连接到我的数据库:

import java.util.*;
import com.microsoft.azure.functions.annotation.*;
import com.microsoft.azure.functions.*;
import java.sql.*;
/**
 * Azure Functions with HTTP Trigger.
 */
public class Function {

    @FunctionName("HttpTrigger-Java")
    public HttpResponseMessage run(
            @HttpTrigger(name = "req", methods = {HttpMethod.GET, HttpMethod.POST}) HttpRequestMessage<Optional<String>> request,
            final ExecutionContext context) throws ClassNotFoundException {

        Connection c = null;

        try {
           Class.forName("org.postgresql.Driver");
           c = DriverManager
                   .getConnection("jdbc:postgresql://<DB server>:5432/<dbname>",
                           "<username>", "<password>");
        } catch (SQLException e) {

           return request.createResponseBuilder(HttpStatus.OK).body(e.getMessage()).build();
        }


       return request.createResponseBuilder(HttpStatus.OK).body("Opened database successfully").build();

    }
}

在maven 依赖项中添加最新的postgresql驱动程序:

<dependency>
  <groupId>org.postgresql</groupId>
  <artifactId>postgresql</artifactId>
  <version>42.2.8.jre7</version>
</dependency>

Azure Java 函数的结果:

enter image description here

关于java - 如何从用 Java 编写的 Azure Function App 连接到 PostgreSQL?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59103862/

相关文章:

java - 在 Android 的字符串中用 ". "替换 "\n\n"

azure - 在 azure 消息总线中使用具有 TCP 中继绑定(bind)的混合连接模式的超时

azure - 在 Azure 中为可用性集设置重复 VM

java - 为什么有些方法中泛型参数<T>会变成<S>

java - 设置工具栏时出现 NullPointerException

java - 从 PL/pgSQL 函数返回行

postgresql - 我无法使用来自 Postgres 数据库的 jooq 3.9.1 获得完整的表列表

postgresql - 从 Postgres 中的时间戳获取两周

c# - 使用 ARM 模板将文件上传到存储帐户

java - 如何在链表中实现泛型 <E>?