【发布时间】:2016-10-17 13:54:17
【问题描述】:
可以使用 java 运行 PL/pgSQL 脚本吗?我正在从 java 代码创建 postgres db,需要在这个 db 上创建一些函数。
我知道我可以像这样使用 DriverManager 运行任何 sql 脚本:
Connection connection = DriverManager.getConnection(
connectionToDbUrl,
getDbUser(),
getDbPassword());
Statement statement = connection.createStatement()
statement.execute("select * from table);
但它不会执行 PL/pgSQL 脚本。有什么想法吗?
编辑:我的意思是 PL/pgSQL
编辑 2:感谢@a_horse_with_no_name 解决方案,我发现了错误。 我使用 BufferedReader 从文件中读取脚本并加入所有行。在每行末尾添加“\n”可以解决问题。
try (BufferedReader br = new BufferedReader(new FileReader(resource.getFile())))
{
statement.execute(br.lines().collect(Collectors.joining(" \n")));
}
【问题讨论】:
-
您的意思是PL/pgSQL 吗?
-
PSQL 基本上是 Postgres 的 shell 或终端,具有许多专有语法。我假设你基本上可以从你的 java 程序中拉出一个命令 shell,但你最好编写实际的 SQL 并通过 JDBC 运行它。
-
@Aaron 是的,我的意思是 PL/pgSQL
-
@a_horse_with_no_name 我想在新数据库上创建函数,而不是运行一个
-
@a_horse_with_no_name 到底有多准确?当脚本在 PL/pgSQL 中时,由 statement.execute 运行会引发异常
标签: java postgresql jdbc plpgsql