title: how to backup and restore mysql database using java
body: <p>I have a small application which I am going to use to backup and restore a mysql database, coding for backup is as follows and it works properly,</p>
  
  <pre><code>....
  String command = "mysqldump --host=" + dataBase.getHost() + " --user=" + dataBase.getUserName() + " --password=" + dataBase.getPassword() + " "
                  + dataBase.getDatabaseName() + " -r " + dataBase.getBackupPath() + "/ofm_mnu_backup_" + bkDate + ".sql";
          System.out.println(command);
          Process p = null;
          try {
  
  
              Runtime runtime = Runtime.getRuntime();
              p = runtime.exec(command);
  
              int processComplete = p.waitFor();
  
              if (processComplete == 0) {
  
                  System.out.println("Backup created successfully");
  
              } else {
                  System.out.println("Could not create the backup");
              }
  ....
  </code></pre>
  
  <p>But when I try to restore the database using following codes it is not working, please help</p>
  
  <pre><code>  ........
      String command = "mysqldump --host=" + dataBase.getHost() + " --user="+dataBase.getUserName() + " --password= " + dataBase.getPassword()+""+dataBase.getDatabaseName() + "  " + dataBase.getBackupPath();
          Process p = null;
  
          try {
              System.out.println(command);
              Runtime runtime = Runtime.getRuntime();
              p = runtime.exec(command);
              int processComplete = p.waitFor();
  
              if (processComplete == 0) {
                  System.out.println("Backup restored successfully");
  
              } else {
                  System.out.println("Could not restore the backup");
              }
       ......
  </code></pre>
  
  <hr>
  
  <p>After so many google searches I found the answer for my matter,</p>
  
  <pre><code>  ......
    String[] executeCmd = new String[]{"mysql", [database], "--user=" + [username],"--password=" + [password], "-e", " source " + [absolute path to the sql file]};
    p = Runtime.getRuntime().exec(executeCmd);
    int processComplete = p.waitFor();
    ......
  </code></pre>
  
  <p>In the above code most important thing is ** " source " + [absolute path to the sql file] ** there shouldn't be a comma between 'source' word and the file path.</p>
  
  <p>this worked for me I hope it'll work for you guys too.</p>