我有一个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函数的结果: