Execute MySQL Script from Java
Ant is a great tool for deployment but I found that it simply wasn’t powerful enough to handle all my needs. So I’ve been developing some deployment tools to make it easier for me to deploy new code releases. One necessity was to be able to execute a MySQL script from Java. The following function will do the job. One note, this function requires that the location of the MySQL executable is in your machine’s path variable.
public static String executeScript (String dbname, String dbuser,
String dbpassword, String scriptpath, boolean verbose) {
String output = null;
try {
String[] cmd = new String[]{"mysql",
dbname,
"--user=" + dbuser,
"--password=" + dbpassword,
"-e",
"\"source " + scriptpath + "\""
};
System.err.println(cmd[0] + " " + cmd[1] + " " +
cmd[2] + " " + cmd[3] + " " +
cmd[4] + " " + cmd[5]);
Process proc = Runtime.getRuntime().exec(cmd);
if (verbose) {
InputStream inputstream = proc.getInputStream();
InputStreamReader inputstreamreader = new InputStreamReader(inputstream);
BufferedReader bufferedreader = new BufferedReader(inputstreamreader);
// read the output
String line;
while ((line = bufferedreader.readLine()) != null) {
System.out.println(line);
}
// check for failure
try {
if (proc.waitFor() != 0) {
System.err.println("exit value = " +
proc.exitValue());
}
}
catch (InterruptedException e) {
System.err.println(e);
}
}
} catch (Exception e) {
e.printStackTrace();
}
return output;
}