I want to export my MySQL database using my java code. But I have not found any way to do. What I want to do that there is a button in my app as "Export Database". When that button is clicked, my database should be exported to specified path. I have used the following code but it does'nt worked :
Runtime runtime = Runtime.getRuntime();
runtime.exec("C:\\Program Files\\MySql\\MySql Server 5.5\\bin\\mysqldump -u root -p myDatabase> D:\\backup.sql");
How should I do this task. Thanks.
Two problems :
Prefer this :
runtime.exec(new String[]{"C:\\Program Files\\MySql\\MySql Server 5.5\\bin\\mysqldump", "-u", "root", "-pmyDatabase" "> D:\\backup.sql"});
Note that if you have a problem with runtime.exec, you should look at the streams you can get from the returned Process. Not looking at those streams in case of error is a little like not looking at the exception when one is thrown.
Backup:
/******************************************************/
//Database Properties
/******************************************************/
String dbName = “dbName”;
String dbUser = “dbUser”;
String dbPass = “dbPass”;
/***********************************************************/
// Execute Shell Command
/***********************************************************/
String executeCmd = “”;
executeCmd = “mysqldump -u “+dbUser+” -p”+dbPass+” “+dbName+” -r backup.sql”;
}
Process runtimeProcess =Runtime.getRuntime().exec(executeCmd);
int processComplete = runtimeProcess.waitFor();
if(processComplete == 0){
out.println(“Backup taken successfully”);
} else {
out.println(“Could not take mysql backup”);
}
Restore:
/******************************************************/
//Database Properties
/******************************************************/
String dbName = “dbName”;
String dbUser = “dbUser”;
String dbPass = “dbPass”;
/***********************************************************/
// Execute Shell Command
/***********************************************************/
String executeCmd = “”;
executeCmd = new String[]{“/bin/sh”, “-c”, “mysql -u” + dbUser+ ” -p”+dbPass+” ” + dbName+ ” < backup.sql” };
}
Process runtimeProcess =Runtime.getRuntime().exec(executeCmd);
int processComplete = runtimeProcess.waitFor();
if(processComplete == 0){
out.println(“success”);
} else {
out.println(“restore failure”);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With