Mysql database backup by using java - java

I am going to take database backup by using java code.This code is excuting fine but I am getting int processComplete = runtimeProcess.waitFor(); This method calling is returning the integer as 1. So finally I am getting the message as could not create backup as sop.
public static void main(String[] args) {
String path = "D:/databasebackup/databasbac.sql";
String username = "root";
String password = "";
String dbname = "rac";
String executeCmd = "<Path to MySQL>/bin/mysqldump -u " + username + " -p" + password + " --add-drop-database -B " + dbname + " -r " + path;
Process runtimeProcess;
try {
// System.out.println(executeCmd);//this out put works in mysql shell
runtimeProcess = Runtime.getRuntime().exec(new String[] { "cmd.exe", "/c", executeCmd });
System.out.println(executeCmd);
// runtimeProcess = Runtime.getRuntime().exec(executeCmd);
int processComplete = runtimeProcess.waitFor();
System.out.println("processComplete"+processComplete);
if (processComplete == 0) {
System.out.println("Backup created successfully");
} else {
System.out.println("Could not create the backup");
}
} catch (Exception ex) {
ex.printStackTrace();
}
}

I was facing similar problem in database backup from MYSQL through JDBC. So I ran the below code.
String path = C:\Program Files\MySQL\MySQL Server 5.7\bin\mysqldump
String command= "cmd.exe /c "
+ "\"\""+path+"\" "
+ " --user="+UserInputs.getDbUserName()
+ " --password="+UserInputs.getDbPassword()
+ " --host="+UserInputs.getDbConnectionIP()
+ " --protocol=tcp "
+ " --port="+UserInputs.getDbConnectionPort()
+ " --default-character-set=utf8 "
+ " --single-transaction=TRUE "
+ " --routines "
+ " --events "
+ "\""+UserInputs.getDbName()
+"\" "
+ ">"
+ " \""
+ "D:\\MY DATA\\DB_Backup.sql"
+ "\""
+ " \"";
Runtime runtime = Runtime.getRuntime(command);
In case password is blank remove the --password line.
This will create your database backup.
In case you are running this on LINUX replace
cmd.exe /c
by
/bin/sh -c
Thanks!

Try out my code for backup the database using java. It works well for me.
try {
String filename = null;
FileChooser.setVisible(true);
int result = FileChooser.showSaveDialog(null);
if (result == JFileChooser.APPROVE_OPTION) {
filename = FileChooser.getSelectedFile().toString().concat(".sql");
File file = new File(filename);
if (file.exists()) {
Object option[] = {"Sim", "Nao"};
int opcao = JOptionPane.showOptionDialog(null, "aaa", "bbbb", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, option, option[0]);
if (opcao == JOptionPane.YES_OPTION) {
Runtime backup = Runtime.getRuntime();
backup.exec("C:\\wamp\\bin\\mysql\\mysql5.6.17\\bin\\mysqldump.exe -v -v -v --host=localhost --user=root --port=3306 --protocol=tcp --force --allow-keywords --compress --add-drop-table --result-file=" + filename + " --databases GIVE YOUR DATABSE NAME");
JOptionPane.showMessageDialog(null, "Backup succesfully");
} else {
FileChooserActionPerformed(evt);
}
} else {
Runtime backup = Runtime.getRuntime();
backup.exec("C:\\wamp\\bin\\mysql\\mysql5.6.17\\bin\\mysqldump.exe -v -v -v --host=localhost --user=root --port=3306 --protocol=tcp --force --allow-keywords --compress --add-drop-table --result-file=" + filename + " --databases GIVE YOUR DATABASE NAME");
JOptionPane.showMessageDialog(null, "Backup succesfully");
}
}
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e, "Error.!", 2);
}
And this is the DbOperation class That i have written.
import com.mysql.jdbc.PreparedStatement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
public class DbOperation {
String url = "jdbc:mysql://localhost:3306/give your database name";
String username = "your username";
String password = "your password";
Connection con = null;
PreparedStatement pst = null;
ResultSet rs = null;
public Connection backupDB(){
try{
con=DriverManager.getConnection(url, username, password);
}catch(SQLException e){
System.out.println(e.getMessage());
}
return con;
}
}

Try this:
int processComplete = runtimeProcess.exitValue();
runtime info
Hope this helps

Related

How to restore MySQL backup file using Runtime process

I'm trying to restore my backup data with this code but nothing
is happening, it's just running my fileName:
C:\DDDD\Backups\DDDD_BD_BackUp_file_2016-04-07_12-06-21.Bak
String[] executeCmd = new String[]{"C:\\Program Files (x86)\\MySQL\\MySQL Server 5.0\\bin\\mysql", "--user=" + User, "--password="+pwd," -h"+host," --port"+port," <"+ fileName};
String executeCmd1="mysql -h "+ host + " --port "+ port +" -u "+ User +" --password="+pwd +" "+nameBase +" -r "+ fileName;
System.out.println(executeCmd);
/*NOTE: Executing the command here*/
Process runtimeProcess = Runtime.getRuntime().exec(executeCmd);
int processComplete = runtimeProcess.waitFor();
/*NOTE: processComplete=0 if correctly executed, will contain other values if not*/
if (processComplete == 0) {
System.out.println("Restore Complete");
} else {
System.out.println("Restore Failure");
}
}} catch (Exception ex) {
System.out.println(ex.toString());
}

Error in backup of MySQL from Java

I have developed a Java application and it's in last stage.
The problem is that I cannot execute the mysqldump with Runtime.getRuntime().exec().
try {
String[] command = new String[] {
"cmd.exe",
"/c",
"mysqldump --host=" + host + " --user=" + dbuser + " --password=" + dbpass + " " + dbname + " > " + filename
};
Process runtimeProcess = Runtime.getRuntime().exec(command);
int ProcessComplete = runtimeProcess.waitFor();
if (ProcessComplete == 0) {
JOptionPane.showMessageDialog(null, "Database backup has been done successfully");
}
else {
JOptionPane.showMessageDialog(null, "Database backup was unsuccessfull");
JOptionPane.showMessageDialog(null, command);
}
}
catch (IOException | InterruptedException exc) {
Logger.getLogger(Backup.class.getName()).log(Level.SEVERE, null, exc);
}
Can anyone help me with this?
I tried your code in Windows and it works fine for me.
Open cmd, type mysqldump and hit enter.
If it is executed successfully, that means your code should work properly if your database configuration is correct.
If you get 'mysqldump' is not recognized as an internal or external command then either you have to set the MySQL path in your environment variable, or specify the full path for mysqldump in your Java code like this:
String[] command = new String[] {
"cmd.exe",
"/c",
"c://mysql/bin/mysqldump --host=" + host + " --user=" + dbuser + " --password=" + dbpass + " " + dbname + " > " + filename
};

Send some input to a Terminal window using Java on Mac OS

I can get a terminal window or command prompt to open on either Mac OS or Windows. I want to send a string to that terminal or cmd window using my java.
String in = " -i " + "\"" + tfIntdta.getText() + "\"";
String rst = " - r " + "\"" + tfRstplt.getText() + "\"";
String out = " -o " + "\"" + tfOutdta.getText() + "\"";
String strip = " -s" + "\"" + tfStpdta.getText() + "\"";
String guistring = "-n gui";
String wd = "\"" + System.getProperty("user.dir");
String osver = System.getProperty("os.name");
String app = "";
if (osver.contains("Mac")){
app = wd + "/relap5.x\"";
} else if (osver.contains("Windows")){
app = "\\relap5.exe";
} else if (osver.contains("linux")) {
app = "/relap5.x";
}
String run = app + in + rst + out;
So the string would look something like this.
"/Users/brianallison/Documents/Java/RELAP5 GUI/issrs/relap5.x" -i "" - r "" -o ""
I want the line above to appear on the terminal or cmd window and execute.
Put your command and parameters in an array:
String[] command = {
"/Users/brianallison/Documents/Java/RELAP5 GUI/issrs/relap5.x",
"-i", "Choose your input file",
"-r", "",
"-o", ""
};
Then execute using Runtime#exec(String[] cmdarray):
Runtime.getRuntime().exec(command);
This answer has been put together after reading your other two questions from today, here and here.

MySql back-up dump file not restored into MySQL database

I have created MySQL backup dump file using Java code. While restoring dump file into MySQL Administrator it is giving MySQL error:
The selected file was generated by mysqldump and cannot be restored by this application.
Below my code for creating MySQL dump file:
public class MysqlBackup {
public boolean backupDataWithDatabase(String dumpExePath, String host, String port, String user, String password, String database, String backupPath) {
boolean status = false;
try {
Process p = null;
DateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");
Date date = new Date();
String filepath = "backup(with_DB)-" + database + "-" + host + "-(" + dateFormat.format(date) + ").sql";
String batchCommand = "";
if (password != "") {
batchCommand = dumpExePath + " -h " + host + " --port " + port + " -u " + user + "< --password=" + password + " --add-drop-database -B " + database + " -r \"" + backupPath + "" + filepath + "\"";
} else {
batchCommand = dumpExePath + " -h " + host + " --port " + port + " -u " + user + " --add-drop-database -B " + database + " -r \"" + backupPath + "" + filepath + "\"";
}
Runtime runtime = Runtime.getRuntime();
p = runtime.exec(batchCommand);
int processComplete = p.waitFor();
if (processComplete == 0) {
FileInputStream in = new FileInputStream(backupPath + "" + filepath);
ZipOutputStream out = new ZipOutputStream(new FileOutputStream("D:\\desktop13\\serverdb.zip"));
out.putNextEntry(new ZipEntry("serverdb.sql"));
byte[] b = new byte[1024];
int count;
while ((count = in.read(b)) > 0) {
out.write(b, 0, count);
}
out.close();
in.close();
status = true;
} else {
status = false;
}
} catch (IOException ioe) {
ioe.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return status;
}
public static void main(String[] args) {
MysqlBackup b = new MysqlBackup();
b.backupDataWithDatabase("D:\\xampp1\\mysql\\bin\\mysqldump.exe", "localhost", "3306", "root", "", "serverdb", "D:\\desktop13");
}
}

MySQL Backup (JAVA)

What are the possible reasons why i can't backup my DB using MYSQLDUMP?
In my localhost, i can backup the db but when I use the db in my hosting, there seems to be a problem. Is it possible that my hosting can't backup db? Btw, im using cloudbees in my database. I'm 100% sure that I change all the username, password and the name of the db when using my hosting MySQL. Actually it creates the .sql file but it is empty.
String executeCmd = "C:/xampp/mysql/bin/mysqldump -u " + username
+ " -p" + password + " somedbname" + " -r "
+ "C:/tech-report-db/backup"
+ c.getTimeInMillis() + c.getWeekYear() + ".sql";
try {
Process runtimeProcess;
runtimeProcess = Runtime.getRuntime().exec(executeCmd);
int processComplete = runtimeProcess.waitFor();
if (processComplete == 0) {
System.out.println("Backup created successfully");
} else {
System.out.println("Could not create the backup");
}
it returns the error "Could not create the backup"
I fixed the problem. Sorry for incomplete question. I'm using a remote mysql so i need to include the hostip and the port
before:
String executeCmd = "C:/xampp/mysql/bin/mysqldump -u " + username
+ " -p" + password + " somedbname" + " -r "
+ "C:/tech-report-db/backup"
+ c.getTimeInMillis() + c.getWeekYear() + ".sql";
now:
String executeCmd = "C:/xampp/mysql/bin/mysqldump -P "+port+ " -h "+hostIP+ " -u " + username
+ " -p" + password + " somedbname" + " -r "
+ "C:/tech-report-db/backup"
+ c.getTimeInMillis() + c.getWeekYear() + ".sql";

Categories

Resources