使用java运行PL / pgSQL脚本

时间:2016-10-17 13:54:17

标签: java postgresql jdbc plpgsql

可以使用java运行PL / pgSQL脚本吗?我是从java代码创建postgres数据库,需要在这个数据库上创建一些函数。

我知道我可以使用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")));
    }

4 个答案:

答案 0 :(得分:1)

这对我有用:

Connection con = DriverManager.getConnection("jdbc:postgresql://localhost/postgres", "...", "******");

Statement stmt = con.createStatement();

String create =
  "create function the_answer() \n" +
  "returns integer as $$\n" +
  "begin \n" +
  "   return 42;\n" +
  "end;\n" +
  "$$\n" +
  "language plpgsql;";

// create the function
stmt.execute(create);

// use the function
ResultSet rs = stmt.executeQuery("select the_answer()");
rs.next();
System.out.println("The answer is: " + rs.getInt(1));

答案 1 :(得分:0)

您应该参考PostgreSQL JDBC文档: https://www.postgresql.org/docs/7.4/static/jdbc-callproc.html

如果你的pgSQL返回一个值,就像那样调用:

ResultSet rs = stmt.executeQuery("SELECT * FROM your_func()");

答案 2 :(得分:0)

PL / pgSQL是调用存储过程(或函数或包)的特殊情况。

您必须使用CallableStatement添加相应的参数。请参阅this示例。

答案 3 :(得分:0)

我遇到了同样的问题,但是我必须以一种略有不同的方式来解决它,我希望在这里与其他人分享。

我发现使用JDBC方法相当笨拙。我想使用一种尽可能接近终端使用pgqsl的方法。

要求1 :作为使用此方法的先决条件,您应该已经可以在终端上运行pgsql命令。

要求2 :如果连接需要密码(否则未指定密码),则用户主目录中的.pgpass文件或PGPASSFILE引用的文件可以包含要使用的密码。该文件应包含以下格式的行:

hostname:port:database:username:password

因此,请在主目录(或您可能真正想要的其他位置,因为以后无论如何都需要引用此位置)中创建文件 .pgpass

要求3 :. pgpass需要受限的访问权限,否则您将收到此错误-.pgpass" has group or world access; permissions should be u=rw (0600) or less。要解决此问题,只需将文件更改为至少600 chmod 600 ~/.pgpass

要求4 :添加这段Java代码以执行您的sql脚本。用您在 .pgpass 文件

中使用的值替换<用户名>,<主机名>和<数据库>
System.setProperty("PGPASSFILE", "~/.pgpass");
Process process = Runtime.getRuntime().exec("psql -U <username> -h <hostname> -d <database> -f src/main/resources/schema.sql");
        try (BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()))) {
            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }
        }
        int ret = process.waitFor();
        System.out.printf("Program exited with code: %d%n", ret);

那应该为您做!