繁体   English   中英

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

[英]How to connect to PostgreSQL from Azure Function App written in Java?

我有一个 Azure 函数应用程序,它有一个用 Java 编写的定时器触发函数。 我需要连接到部署在其中一个 Azure VM 上的 PostgreSQL(此处不使用 Managed 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 dependencies添加最新的 postgresql 驱动程序:

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

Azure Java 函数的结果:

在此处输入图片说明

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM