• Technical
  • How to create MySql backup and archive it using Java
Header

How to create MySql backup and archive it using Java

Hi Guys,

I know, the first question is “why” as a lot of tools, both free and commercial, are available to do the same thing. It’s fun ๐Ÿ™‚ and may be it can give you general idea how those tools actually work internally.

urlFour main implementations:
1. Taking MySql database backup in .sql file
2. Putting .sql file in folder
3. Creating archive of this folder.
4. And finally copying archive file to a particular location.

 

 

So, let’s see the code.

Configurations:

DB_HOST_BK = localhost
DB_USER_BK = username
DB_PASS_BK = password
DB_NAME_BK = databasename /* name of the database to backed up */
DB_PORT_BK = 3306
DESTI_FOLDER_NAME = /destination/path/for/folder
DB_EXE_PATH = /usr/bin/mysqldump
DESTI_ZIP_PATH = /destination/path/for/archive

Take MySql backup:

package com.mysql.backup;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.FileOutputStream;
import java.io.File;
import java.util.Date;
import java.text.DateFormat;
import java.text.SimpleDateFormat;


/**
 * Takes backup of database
 * 
 * @author Nitesh Apte
 * @version 1.0
 * @license GPL
 */
public class DatabaseBackup {
  
  private int STREAM_BUFFER = 512000;

  public boolean backupDatabase(String host, String port, String user, String password, String dbname, String rootpath, String dbexepath) {
  
    boolean success = false;
    try{
      String dump = getServerDumpData(host, port, user, password, dbname, dbexepath);
      if(!dump.isEmpty()) {
        byte[] data = dump.getBytes();
      
        File file = new File(rootpath + "/" + dbname);
        if(!file.isDirectory()) {
          file.mkdir();              
        }
        
        DateFormat dateFormat = new SimpleDateFormat("yyyyMMddHms");
        Date date = new Date();
        String filepath = rootpath + dbname + "/" + dbname + dateFormat.format(date) + ".sql";
        File filedst = new File(filepath);
        FileOutputStream dest = new FileOutputStream(filedst);
        dest.write(data);
        dest.close();
        success = true;
      } 
    } catch (Exception ex) {
      ex.printStackTrace();
    }
    return success;
  }
  
  public String getServerDumpData(String host, String port, String user, String password, String db, String mysqlpath) {
    
        StringBuilder dumpdata = new StringBuilder();
        String execline = mysqlpath;
        try {
          if(host!=null && user!=null && password!=null && db!=null) {
      
            String command[] = new String[]{execline,
                                "--host=" + host,
                                "--port=" + port,
                                "--user=" + user,
                                "--password=" + password,
                                "--compact",
                                "--complete-insert",
                                "--extended-insert",
                                "--skip-comments",
                                "--skip-triggers",
                                db};

            ProcessBuilder pb = new ProcessBuilder(command);
            Process process = pb.start();
            InputStream in = process.getInputStream();
            BufferedReader br = new BufferedReader(new InputStreamReader(in));

            int count;
            char[] cbuf = new char[STREAM_BUFFER];
            
            while ((count = br.read(cbuf, 0, STREAM_BUFFER)) != -1){
              dumpdata.append(cbuf, 0, count);
            }
            br.close();
            in.close();
          }
        } catch (Exception ex) {
          ex.printStackTrace();
          return "";
        }
        return dumpdata.toString();
  }
}

Folder related activities:

package com.mysql.backup;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;


/**
 * Create zip of folder
 * 
 * @author Nitesh Apte
 * @version 1.0
 * @license GPL
 */
public class FolderBackup{
  
  public Boolean zipFolder(String srcFolder, String destZipFile) throws Exception {
    ZipOutputStream zip = null;
    FileOutputStream fileWriter = null;

    fileWriter = new FileOutputStream(destZipFile);
    zip = new ZipOutputStream(fileWriter);
    addFolderToZip(srcFolder, zip);
    zip.flush();
    zip.close();
    return true;
  }

  public void addFileToZip(String srcFile, ZipOutputStream zip) throws Exception {
    File folder = new File(srcFile);
    if (folder.isDirectory())
 {
      addFolderToZip(srcFile, zip);
    } else {
      byte[] buf = new byte[1024];
      int len;
      FileInputStream in = new FileInputStream(srcFile);
      zip.putNextEntry(new ZipEntry("/" + folder.getName()));
      while ((len = in.read(buf)) > 0) {
        zip.write(buf, 0, len);
      }
    }
  }

  public void addFolderToZip(String srcFolder, ZipOutputStream zip) throws Exception {
    File folder = new File(srcFolder);
    for (String fileName : folder.list()) {
      addFileToZip(srcFolder + "/" + fileName, zip);
    }
  }
}

Now, the management:

package com.mysql.backup;

import java.io.IOException;
import java.math.BigInteger;
import java.util.Date;
import java.util.Properties;
import java.text.DateFormat;
import java.text.SimpleDateFormat;

/**
 * Datavault Manager
 * 
 * @author Nitesh Apte
 * @version 1.0
 * @license GPL
 */
public class BackUpManager {

  public String DB_HOST;
  public String DB_NAME;
  public String DB_PORT;
  public String DB_USER;
  public String DB_PASS;
  public String FOLDER_NAME;
  public String DB_EXE;
  public String DESTINATION;

  public BigInteger timeNoted;
  String projectName = new String();

  private static final String PROP_FILE = "config.properties";

  public BackUpManager() {		
    readConfiguration();		
  }
  
  public void readConfiguration() {
    try {
      Properties prop = new Properties();
      prop.load(this.getClass().getResourceAsStream(PROP_FILE));

      DB_HOST = prop.getProperty("DB_HOST_BK");
      DB_NAME = prop.getProperty("DB_NAME_BK");
      DB_PORT = prop.getProperty("DB_PORT_BK");
      DB_USER = prop.getProperty("DB_USER_BK");
      DB_PASS = prop.getProperty("DB_PASS_BK");
      FOLDER_NAME = prop.getProperty("DESTI_FOLDER_NAME");
      DB_EXE = prop.getProperty("DB_EXE_PATH");
      
      DESTINATION = prop.getProperty("DESTI_ZIP_PATH");
      
    } catch (IOException e) {
      System.out.println("Cannot read the property file.");
    }
  }

  public Boolean databaseBackup() {
    if(new DatabaseBackup().backupDatabase(DB_HOST, DB_PORT, DB_USER, DB_PASS, DB_NAME, FOLDER_NAME, DB_EXE)) {
      return true;
    } else {
      return false;
    }
  }

  public Boolean folderBackup() throws Exception {
    if(new FolderBackup().zipFolder(FOLDER_NAME + "/" + DB_NAME , DESTINATION + "/" + DB_NAME + ".zip")) {
      DateFormat dateFormat = new SimpleDateFormat("yyyyMMddHms");
      Date nowtime = new Date();
      timeNoted = BigInteger.valueOf(Long.parseLong(dateFormat.format(nowtime)));
      return true;
    } else {
      return false;
    }
  }

  public static void main(String[] args) {

    BackUpManager dm = new BackUpManager();
    try {
      if(dm.databaseBackup()) {
        if(dm.folderBackup()) {
          System.out.println("Process complete.");
        } else {
          System.out.println("Folder backup process failed.");
        }
      } else {
        System.out.println("Process failed.");
      }
    } catch (Exception e) {
      e.printStackTrace();
    }	
  }
}

Keep the MySql connector jar in classpath ๐Ÿ™‚

Soon, I will create a repository in Github.

 

That’s it guys.

Critics/suggestions are very much welcome.

Have a nice day ahead!

5,017 total views, 1 views today

This entry was posted in Technical

3 Responses



Leave a Reply

Your email address will not be published. Required fields are marked *

Time limit is exhausted. Please reload CAPTCHA.

Follow Me