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;
}
}
}
-
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 codeMayur– Mayur2024-02-09 12:02:13 +00:00Commented Feb 9, 2024 at 12:02
-
1Java 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 Commandaled– aled2024-02-09 12:25:40 +00:00Commented Feb 9, 2024 at 12:25
Add a comment
|
1 Answer
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;
}