【问题标题】:running psql command in a java program在 java 程序中运行 psql 命令
【发布时间】:2019-05-30 21:22:33
【问题描述】:

我有一个要求,我需要使用 java 代码创建/删除/更改 postgres 表。

我写了一个程序如下:

public static void main(String[] args) throws IOException {
        System.out.println("Hello World!");
        Process p = Runtime.getRuntime().exec("psql -U postgres -d testdb -h localhost -p 5433 -f D:\test.sql");
    }

test.sql 文件如下所示,

Create TABLE MyTable1
(
    VersionNumber VARCHAR(32) NOT NUll
);

Create TABLE MyTable2
(
    VersionNumber VARCHAR(32) NOT NUll
);

Create TABLE MyTable3
(
    VersionNumber VARCHAR(32) NOT NUll
);

问题:

如果我运行相同的 psql 命令:

psql -U postgres -d testdb -h localhost -p 5433 -f D:\test.sql

在命令行中,它要求输入密码并创建表。

但是在java程序中,没有提供密码的规定。请告诉我如何实现它。

【问题讨论】:

    标签: java postgresql psql


    【解决方案1】:

    您可以改用connection URL

    psql -f d:\test.sql postgresql://postgres:password@localhost:5433/testdb
    

    【讨论】:

    • 我使用的是 postgres 10.5 版本。好吗
    【解决方案2】:

    首先,最好实际使用 JDBC 连接数据库并运行您的 SQL 语句。如果您设置使用命令行 psql,您可以使用PGPASSWORD 环境变量来设置密码:

    String command = "psql -U postgres -d testdb -h localhost -p 5433 -f D:\test.sql";
    String[] envVars = { "PGPASSWORD=yourpassword" };
    Process p = Runtime.getRuntime().exec(command, envVars);
    

    如有必要,您可以从stdin 读取密码。但是,同样,最好通过 JDBC 执行此操作。

    【讨论】:

    • 对不起.. 这不起作用。如果我将 PGPASSWORD 直接设置为系统变量,那么它可以工作。如果我从系统变量中删除条目并尝试使用您的方法,它不起作用。能否请您也检查一次。
    【解决方案3】:

    关于a_horse_with_no_nameanswer 并在 Windows 操作系统上使用 psql 的 Java 代码启动 并使用ProcessBuilder 以下轻微修改对我有用

        ProcessBuilder builder = new ProcessBuilder();
        String connUrl = "postgresql://user:password@host:port/dbname";
        String sqlFileToProcess = "--file=Disk:\\path\\to\\file.sql";
        builder.command("psql.exe", sqlFileToProcess, connUrl);
        builder.directory(new File("Disk:\\Path\\to\\psql\\containing\\folder"));
        Process process = builder.start();
        int exitCode = 0;
        try {
             exitCode = process.waitFor();
             int len;
             if ((len = process.getErrorStream().available()) > 0) {
                 byte[] buf = new byte[len];
                 process.getErrorStream().read(buf);
                 System.err.println("Command error:\t\""+new String(buf)+"\"");
             }
        } catch (InterruptedException e) {
             e.printStackTrace();
        }
       assert exitCode == 0;
    

    不知道为什么,但是如果:

    -f Disk:\\path\\to\\file.sql
    

    作为 Java 代码中的参数 throws:

    Command error:  "unrecognized win32 error code: 123 psql: error:  Disk:/path/to/file.sql: Invalid argument
    "
    

    (注意输出和输入中斜杠和反斜杠的重定向)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-04-10
      • 1970-01-01
      • 1970-01-01
      • 2021-04-08
      • 2011-04-11
      • 1970-01-01
      相关资源
      最近更新 更多