Execute MySQL Script from Java
Code January 20th, 2005Ant 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;
}








January 11th, 2006 at 2:50 pm
Hello,
This script seems to work OK for me on Windows but I get a SQL syntax ‘”source myfile”‘ please check you code message when running on Linux.
Did this code work on linux for you??
January 11th, 2006 at 10:59 pm
hi bernard,
yes i have also run this on linux with no problem. perhaps you have a different version of mysql on your linux box.
January 8th, 2008 at 11:15 am
Hi,
In Windows, it’s quite alright(although I had to add “cmd” to the commands list). But in Linux, it does not work anyway. I get exit value=1, but nothing else happens, beyond the schema I try to use seems to get locked. But the most strange is that if I try to type the same commands in command line, it works pretty fine, what makes me think that mysql version isn`t the issue.
Any ideas?
Regards.