0
public class DumpFileClass{   

  public static boolean importDump(String host, String username, String password, String database, String dumpFilePath) {
           
            
            String mysqlCommand = "mysql -h " + host + " -u " + username + " -p" + password +" " + database + " < " + dumpFilePath;
            System.out.println(mysqlCommand);
            try {
                Process process = Runtime.getRuntime().exec(mysqlCommand);
                logger.trace(process);
                int exitCode = process.waitFor();
                logger.trace(exitCode);
                System.out.println(exitCode);

                return exitCode == 0;
            } catch (IOException | InterruptedException e) {
                e.printStackTrace();
                return false;
            }
        }
 }
2
  • I have specified all the correct credentials in the code but it is not pushing the data into the new db even though not throwing any exceptions (program also not terminating). I can do the same process by using cmd prompt but getting trouble with java code Commented Feb 9, 2024 at 12:02
  • 1
    Java doesn't do redirection like the shell. And don't use Runtime exec(). Use ProcessBuilder instead. Does this answer your question? Using Java ProcessBuilder to Execute a Piped Command Commented Feb 9, 2024 at 12:25

1 Answer 1

0

You can avoid your dependence on the shell by writing to the process input stream. Also avoid dependence on passing a parameter of the database name to mysql, as that's not relevant usually when restoring a dump:

    public static boolean importDump(String host, String username, String password, 
            String dumpFilePath) {
        boolean result = false;
        String[] mysqlCommand = { "mysql",  "-h", host, "-u", username, "-p" + password };
        try {
            ProcessBuilder pb = new ProcessBuilder(mysqlCommand).redirectError(Redirect.INHERIT).redirectOutput(Redirect.INHERIT);
            Process process = pb.start();
            try (InputStream in = Files.newInputStream(Path.of(dumpFilePath));
                OutputStream out = process.getOutputStream()) {
                in.transferTo(out);
            }
            logger.trace(process);
            int exitCode = process.waitFor();
            logger.trace(exitCode);
            result = (exitCode == 0);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.