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;
}
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??
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.
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.
Hi All,
This works fine in windows. However im facing some issues in LINUX. Any one have any idea please share with me..?
Regards,
Prabhu.
Hi,
I have the same problem as Felipe. I run the java code and the only output I get is “exit value = 1″ . But if I run the same command in a shell it runs perfect. Anybody has any idea?Maybe is the path to the script that i want to run?
thanks in advance.
Hello,
I have the solution:
use “source ” + scriptpath instead… donĀ“t use the “\”" for linux.
good luck