Hi friends…
When you working with database projects don’t you ever felt how to get Backup or restore of the MySQL database? I got that point and searched on the internet. Then I got lot of examples and some of them were not worked. Then I changed some parts of the codes and finally I used it in my project. Here I want to tell something. If you use Microsoft Windows 7 or Vista i think you will not able to create backup on the c: directory. There for I have changed the backup path into d: directory and I am using MySQL server 5.1 on my machine. I have created a java project with simple GUI and I have put two buttons to get backups and restores. Here below you can see the methods and you can use now this code inside your project.

Code for backup MySQL database

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed

try{

int processComplete; // to verify that either process completed or not

Process runtimeProcess = Runtime.getRuntime().exec("C:\\Program Files\\MySQL\\MySQL Server 5.1\\bin\\mysqldump -u root -p1234 mysql -r D:/backup.sql");

// call the mysqldump in terminal and execute it

processComplete = runtimeProcess.waitFor();//store the state in variable

if(processComplete==1){//if values equal 1 process failed

JOptionPane.showMessageDialog(null, "Backup Failed");//display message
}

else if(processComplete==0){//if values equal 0 process failed

JOptionPane.showMessageDialog(null,"\n Backup created Successfully..\n Check the Backup File in the D: Directory named as backup.sql");
//display message
}

}catch(Exception e){

JOptionPane.showMessageDialog(null,e);//exeception handling

}

// TODO add your handling code here:
}//GEN-LAST:event_jButton1ActionPerformed

Code for Restore MySQL database

private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed 

try{

String databaseName="mysql";//database name
String userName="root";//username of mysql
String password="1234";//password of myql
int processComplete;// this variable for verify the process

String[] executeCmd = new String[]{"mysql", databaseName, "-u" + userName, "-p" + password, "-e", " source D:/backup.sql" };
//sava the command in a array
Process runtimeProcess = Runtime.getRuntime().exec(executeCmd);// execute the command

processComplete = runtimeProcess.waitFor();// get the result to variable

if(processComplete==1){// if return value equal to 1 then failed the process

JOptionPane.showMessageDialog(null, "Restore Failed");
}

else if(processComplete==0){{// if return value equal to 0 then failed the process

JOptionPane.showMessageDialog(null, "Restore Completed");

}
}

}
catch(Exception ex){

JOptionPane.showMessageDialog(null, ex);

}

// TODO add your handling code here:
}//GEN-LAST:event_jButton2ActionPerformed

You can download the completes NetBeans project from

Here

24 thoughts on “Get Backup and Restore on MySQL in java

    1. there maybe not a backup file to be restored. So please check the file first.another thing is if you are use windows 7 or vista you can’t create backup file on the c directory.You have to select another path or reduce security level of the PC. Best thing is change the backup path..

      Let me know whether you successful or not.

  1. Dear Damith,

    Can change fonts in columns in table in java? That means if there five column.can we set five fonts to those column?If you know the way pleses post a code for that.

    Isuru

  2. @isuru

    try with:

    String[] executeCmd = new String[]{“C:\\Program Files\\MySQL\\MySQL Server 5.1\\bin\\mysql”, databaseName, “-u” + userName, “-p” + password, “-e”, ” source D:/backup.sql” };

  3. Mr Damith…. the code for restore gives a JavaIOException as follows –

    java.io.IOException: Cannot run program "mysql": CreateProcess error=2, The system cannot find the file specified

    but th backup file is present in that location and is created by ur code…
    .Please help me.it’s Urgent.Thanks

    1. Mr, Vibhakar when this problem occur.I mean in backup process or in re-store process.If you that error on re-store process check whether you have a backup file in the path.Let me know the result

      1. Mr. Damith, this problem occurs in restoration. Yes the backup file is in the path i.e., “D” Directory. Backup works fine.

        If u dont mind i also want to ask that when i restore the backup file created through your code, the same fie is not restored by My SQL Administrator. It says to check the field “Ignore Errors”. When i check that field, then also an error occurs which says –

        Error while executing this query:DROP TABLE IF EXISTS `def`;
        The server has returned this error message:No database selected
        Error while executing this query:CREATE TABLE `def` (
        `name` varchar(50) DEFAULT NULL
        ) ENGINE=InnoDB DEFAULT CHARSET=latin1;
        The server has returned this error message:No database selected
        Error while executing this query:LOCK TABLES `def` WRITE;
        The server has returned this error message:No database selected
        Error while executing this query:/*!40000 ALTER TABLE `def` DISABLE KEYS */;
        The server has returned this error message:No database selected
        Error while executing this query:INSERT INTO `def` VALUES (‘a’),(‘d’),(‘b’),(‘h’),(‘m’),(‘v’),(‘g’);
        The server has returned this error message:No database selected
        Error while executing this query:/*!40000 ALTER TABLE `def` ENABLE KEYS */;
        The server has returned this error message:No database selected

        . Please Help. Thanks.

  4. Mr Damith,
    i tried the code for restore,but it didn’t work. not restore nor any error msg.
    And the result of processComplete is 1.
    i really have no idea what the pro is. Please help me .Thanks.

  5. Mr. Damith, I got it. Actually when I downloaded your project folder and changed db name, password and my desired path. it worked. I dont know why it dint work. but thank GOD and Of course you for helping me.

    One more question, when i imported your project it asked for Installing JUnit
    Can you explain why it did so??

    Thanks Once Again Mr. Damith.

  6. Now , I figured out why at first i could not restore. Actually i was restoring database other than the default “mysql” database. In the code of your project database name is “mysql”. Bt when other database like, “abc” are restored, then an Error prompts – “Restoration failed.”… P;ease help……

  7. Your backup code is up to date but in restore code you have missed the full path of mysql. Your help is really valuable. Thank you.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s