Вопрос

I have a .bat file that executes the psql command to import a SQL script file. When I execute the .bat file from Windows command line, it executes correctly. But when I call the .bat file from Java (with ProcessBuilder), the script doesn't end. I'm not getting any errors, not in the InputStream, the ErrorStream not even in the DB (Postgresql) log.

ArrayList<String> cmdArgs2 = new ArrayList<String>();
        cmdArgs2.add("sql2dbs.bat");


        ProcessBuilder pb2 = new ProcessBuilder(cmdArgs2);
        logger.info(pb2.command().toString());

        Map<String, String> env = pb2.environment();
        env.put("PGPASSWORD", "user");

        Process p2 = pb2.start();

        BufferedReader stdError2 = new BufferedReader(new InputStreamReader(p2.getErrorStream()));
        String s;
        while ((s = stdError2.readLine()) != null) {
            logger.info(s);
        }

        BufferedReader stdIn = new BufferedReader(new InputStreamReader(p2.getInputStream()));
        while ((s = stdIn.readLine()) != null) {
            logger.info(s);
        }

        p2.waitFor();

The SQL script is very long that's why I'm not adding it. The script does have a COMMIT statement at the bottom.

Any ideas? Thanks,

Это было полезно?

Решение

Don't run batch scripts using psql to import data into a database. psql is made for interactive use, not to be (ab)used as an API. You can do this directly in Java via JDBC, see for instance here or here. Using JDBC will also give you far better control and debugging options compared to shelling out.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top