MySQL Database Backup & Restore Using Java

Hello Programmers !!

It’s been a while I’ve written a blog post. Luckily I’m in a mood to write something at the moment. Today I thought about posting something I’ve learnt recently. It’s about database backups and restores through java.

If anyone wants to backup or restore a database without going through all these troubles, you can simply use MySQL GUI Tools Bundle freely distributed by the Oracle Corporation.

Sometimes it is necessary to integrate a backup & restore system to an application we are developing. In my case it was a java application. In this post I’m expecting to give you guys a rough idea about backing up and restoring your MySQL database through a Java Application.

1. Creating A Backup

When we install MySQL open source database it provides us a client called mysqldump for backup purposes. Here we execute this mysqldump command using the java Runtime.

Here’s a sample method to create a complete database backup including add, drop MySQL statements.

public boolean backupDB(String dbName, String dbUserName, String dbPassword, String path) {

        String executeCmd = "mysqldump -u " + dbUserName + " -p" + dbPassword + " --add-drop-database -B " + dbName + " -r " + path;
        Process runtimeProcess;
        try {

            runtimeProcess = Runtime.getRuntime().exec(executeCmd);
            int processComplete = runtimeProcess.waitFor();

            if (processComplete == 0) {
                System.out.println("Backup created successfully");
                return true;
            } else {
                System.out.println("Could not create the backup");
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }

        return false;
    }

Basically what we are doing here is similar executing the following command in the windows command line.

mysqldump -u Username -pPassword --add-drop-database -B databaseName -r backupPath

Here  -u, -p, -B, -r are options to indicate that we are inserting the database username, password, database name and location to save the backup respectively. The --add-drop-database option is to create a complete backup. It means that when we are restoring the backup file, if the database does not exist in that particular database the restoring process itself create the database automatically.

If by any chance you want to create a backup without add, drop database command. You can use the following command.

mysqldump -u Username -pPassword databaseName -r backupPath

For multiple databases use

mysqldump -u Username -pPassword --add-drop-database -B db1 db2 db3 -r backupPath

If you want to backup All the databases. You can use the command as follows.

mysqldump -u Username -pPassword --add-drop-database -A -r backupPath

Likewise you can create your backup according to the requirements. There are many other options that you can add to your command. You can visit mysqldump Docs for more options or simply type mysqldump --help on the command line to view the options.

That’s the basic idea about backing up the database. Let’s see how we can do the restoring process through java.

2. Restoring A Backup

I had hard time finding a working code for the restoring process. After making a few changes on the commands I’ve found on the internet, I’ve manage to create a workable runtime  command for the restore process.

Note: The following method is to restore a complete database backup (backup with add, drop database command)

public boolean restoreDB(String dbUserName, String dbPassword, String source) {

        String[] executeCmd = new String[]{"mysql", "--user=" + dbUserName, "--password=" + dbPassword, "-e", "source "+source};

        Process runtimeProcess;
        try {

            runtimeProcess = Runtime.getRuntime().exec(executeCmd);
            int processComplete = runtimeProcess.waitFor();

            if (processComplete == 0) {
                System.out.println("Backup restored successfully");
                return true;
            } else {
                System.out.println("Could not restore the backup");
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }

        return false;
    }

If the the backup doesn’t have the add, drop database, you can use the following method.

public static boolean restoreDB(String dbName, String dbUserName, String dbPassword, String source) {

        String[] executeCmd = new String[]{"mysql", "--user=" + dbUserName, "--password=" + dbPassword, dbName,"-e", "source "+source};

        Process runtimeProcess;
        try {

            runtimeProcess = Runtime.getRuntime().exec(executeCmd);
            int processComplete = runtimeProcess.waitFor();

            if (processComplete == 0) {
                System.out.println("Backup restored successfully");
                return true;
            } else {
                System.out.println("Could not restore the backup");
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }

        return false;
    }

I have tested all the commands and the methods mentioned in this post and they worked fine in Windows environment. That’s all about creating & restoring backups. Hope you guys learnt something new.
If you have any questions please post them as a comment & I’ll try my best to answer them. I’m backing up for now then. See you guys with another post. Hopefully! :)
References:
http://sureshk37.wordpress.com/2009/09/07/mysql-backup-and-restore-using-java/
http://forums.mysql.com

17 Responses to MySQL Database Backup & Restore Using Java

  1. package files;

    import java.util.*;
    import java.io.*;
    public class tableBackup_1 {
    public boolean tbBackup(String dbName, String tbName, String dbUserName, String dbPassword, String path) {

    String executeCmd = “mysqldump -u ” + dbUserName + ” -p” + dbPassword +”"
    + dbName + “–tables” + tbName + ” -r ” + path;

    Process runtimeProcess;
    try {
    runtimeProcess = Runtime.getRuntime().exec(executeCmd);
    int processComplete = runtimeProcess.waitFor();

    if (processComplete == 0) {
    System.out.println(“Backup created successfully”);
    return true;
    } else {
    System.out.println(“Could not create the backup”);
    }
    } catch (Exception ex) {
    ex.printStackTrace();
    }
    return false;
    }
    public static void main(String[] args){
    tableBackup_1 bb = new tableBackup_1();
    bb.tbBackup(“nsetrans”,”price”, “root”, “sa”, “C:/New Folder/table.sql”);

    }
    }

    ******** not working pls. what am i doing wrong?

    • Replace your executeCmd with this:

      String executeCmd = "mysqldump -u " + dbUserName + " -p" + dbPassword + " "
      + dbName + " --tables " + tbName + " -r " + path;

      And change your path like this: "\"C:/New Folder/table.sql\""

      when your folder name has a space, you should include the path within double quotations.
      should work fine

  2. Thank you for answer, I have question,
    in my computer problem with mysqldump
    java.io.IOException: Cannot run program “mysqldump”: CreateProcess error=2, The system cannot find the file specified

    • Check whether you have given the path to the dump file correctly. If it doesn’t solve your problem, post your code here. I can check it for you if you like.

    • Follow this example:

      String[] executeCmd = new String[]{"mysql", "--host=" + dbIP, "--user=" + dbUserName, "--password=" + dbPassword, dbName,"-e", "source "+source};

      Replace ‘dbIP’ with the IP of your server (ex: 192.168.1.25). The username you’re using should have privileges to access the database remotely.

      • but i have to execute this code on the from remote pc right??
        i am creating a backup of db in pc1 and from pc1 i wnt to restore it to pc2.
        so what do i do??

  3. Got this problem on windows xp. what is the cause.

    ERROR com.busytech.barba.exception.BarbaException – java.io.IOException: Cannot run program “C:\Program”: CreateProcess error=2, The system cannot find the file specified
    com.busytech.barba.exception.BarbaException: Cannot run program “C:\Program”: CreateProcess error=2, The system cannot find the file specified
    at com.busytech.barba.persistence.BackUpAndRestoreDatabaseManager.getTableBackup(BackUpAndRestoreDatabaseManager.java:52)
    at com.busytech.barba.servlet.checkcash.CashSummaryServlet.processRequest(CashSummaryServlet.java:95)
    at com.busytech.barba.servlet.checkcash.CashSummaryServlet.doPost(CashSummaryServlet.java:495)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:637)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:298)
    at org.apache.coyote.http11.Http11AprProcessor.process(Http11AprProcessor.java:864)
    at org.apache.coyote.http11.Http11AprProtocol$Http11ConnectionHandler.process(Http11AprProtocol.java:579)
    at org.apache.tomcat.util.net.AprEndpoint$Worker.run(AprEndpoint.java:1665)
    at java.lang.Thread.run(Unknown Source)
    java.io.IOException: Cannot run program “C:\Program”: CreateProcess error=2, The system cannot find the file specified
    at java.lang.ProcessBuilder.start(Unknown Source)
    at java.lang.Runtime.exec(Unknown Source)
    at java.lang.Runtime.exec(Unknown Source)
    at java.lang.Runtime.exec(Unknown Source)
    at com.busytech.barba.persistence.BackUpAndRestoreDatabaseManager.getTableBackup(BackUpAndRestoreDatabaseManager.java:30)
    at com.busytech.barba.servlet.checkcash.CashSummaryServlet.processRequest(CashSummaryServlet.java:95)
    at com.busytech.barba.servlet.checkcash.CashSummaryServlet.doPost(CashSummaryServlet.java:495)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:637)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:298)
    at org.apache.coyote.http11.Http11AprProcessor.process(Http11AprProcessor.java:864)
    at org.apache.coyote.http11.Http11AprProtocol$Http11ConnectionHandler.process(Http11AprProtocol.java:579)
    at org.apache.tomcat.util.net.AprEndpoint$Worker.run(AprEndpoint.java:1665)
    at java.lang.Thread.run(Unknown Source)
    Caused by: java.io.IOException: CreateProcess error=2, The system cannot find the file specified
    at java.lang.ProcessImpl.create(Native Method)
    at java.lang.ProcessImpl.(Unknown Source)
    at java.lang.ProcessImpl.start(Unknown Source)
    … 21 more
    347156 [http-8080-4] ERROR com.busytech.barba.exception.BarbaException – java.io.IOException: Cannot run program “C:\Program”: CreateProcess error=2, The system cannot find the file specified
    com.busytech.barba.exception.BarbaException: Cannot run program “C:\Program”: CreateProcess error=2, The system cannot find the file specified
    at com.busytech.barba.persistence.BackUpAndRestoreDatabaseManager.getTableBackup(BackUpAndRestoreDatabaseManager.java:52)
    at com.busytech.barba.servlet.checkcash.CashSummaryServlet.processRequest(CashSummaryServlet.java:95)
    at com.busytech.barba.servlet.checkcash.CashSummaryServlet.doPost(CashSummaryServlet.java:495)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:637)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:298)
    at org.apache.coyote.http11.Http11AprProcessor.process(Http11AprProcessor.java:864)
    at org.apache.coyote.http11.Http11AprProtocol$Http11ConnectionHandler.process(Http11AprProtocol.java:579)
    at org.apache.tomcat.util.net.AprEndpoint$Worker.run(AprEndpoint.java:1665)
    at java.lang.Thread.run(Unknown Source)

    • From the look at it, it may be an error with your backup file path. Usually a path is given as follows in case you don’t know "\"C:/New Folder/table.sql\""

      If the problem still exist, put your Backup/Restore method as here. I’ll try my best to find the error.

  4. hello,
    I tested this code on windows, but it doesn’t work
    java.io.IOException: Cannot run program “mysqldump”: CreateProcess error=2
    maybe because before executing mysqldump in the windows command line i have to specify it’s path .Otherwise it worked perfectly on linux.
    Can you tell me what is the problem!
    sorry for my english :$ and thank you for this blog it’s really interesting

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 )

Connecting to %s