Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exporting database through my java code

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.

like image 994
Muhammad Salman Farooq Avatar asked Jan 15 '23 16:01

Muhammad Salman Farooq


2 Answers

Two problems :

  • the space between -p and the password
  • the space inside the path to the executable

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.

like image 138
Denys Séguret Avatar answered Jan 22 '23 18:01

Denys Séguret


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”);

}
like image 29
Mehdi Avatar answered Jan 22 '23 18:01

Mehdi