Choose Your Language

Thursday, 22 October 2015

java program to backup mysql database

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package test;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.zip.Deflater;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 *
 * @Aravind Sankaran Nair
 */
public class BackUpDatabase {
  
    public static void main(String ar[]){
        getMysqlDatabaseBackUp();
    }
   public static void getMysqlDatabaseBackUp() {
   String backUpPath = "D:\\test";   /* driveName:\\folderName      */
   String host="localhost";
   String mysqlPort="3306";
   String dbUser="root";
   String dbPassword ="root";
   String database ="qualitychecker";    /* database bame */
   BackUpDatabase  b = new BackUpDatabase ();
   try
  {
       DateFormat dayFormat = new SimpleDateFormat("dd");
       DateFormat monthFormat = new SimpleDateFormat("MM");
       DateFormat yearFormat = new SimpleDateFormat("yyyy");
       Calendar cal = Calendar.getInstance();
       String backupDate=dayFormat.format(cal.getTime())+"-"+monthFormat.format(cal.getTime())+"-"+yearFormat.format(cal.getTime());
     
 byte[] data = b.getData(host, mysqlPort, dbUser, dbPassword, database).getBytes();
      
       /* To Make Zip file that holding this database use these lines
         File fileDestination = new File(backUpPath+"\\"+database+".zip");
         FileOutputStream destination = new FileOutputStream(fileDestination);
         ZipOutputStream zip = new ZipOutputStream(new BufferedOutputStream(destination));
         zip.setMethod(ZipOutputStream.DEFLATED);
         zip.setLevel(Deflater.BEST_COMPRESSION);             
         zip.putNextEntry(new ZipEntry(database+"_backup_"+backupDate+".sql"));
         zip.write(data);
         zip.close();
          */
       File fileDestination = new File(backUpPath+"\\"+database+"_"+backupDate+".sql");
       FileOutputStream destination = new FileOutputStream(fileDestination);      
       destination.write(data);
      
       destination.close();
   
  System.out.println("Back Up Success");
  }catch (Exception ex){
       System.out.println("Back Up Failed");
       ex.printStackTrace();
  }        
}
   
    private static ResultSet rs;
    private static Connection con;
    private Statement st;
    private int BUFFER = 99999;
    public String getData(String host, String port, String user, String password, String db) {
        String Mysqlpath = getMysqlBinPath(user, password, db);
        try {
            Class.forName("com.mysql.jdbc.Driver");
        } catch (Exception e) {
            e.printStackTrace();
            System.out.print("cant access mysql driver");
        }
        try {
            con = DriverManager.getConnection("jdbc:mysql://localhost:3306/" + db, user, password);
            st = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
        } catch (Exception e) {
            System.out.print("connection error");
            e.printStackTrace();
        }
            System.out.println(Mysqlpath);
        Process run = null;
        try {
            System.out.println(Mysqlpath + "mysqldump --host=" + host + " --port=" + port + " --user=" + user + " --password=" + password + " --compact --complete-insert --extended-insert " + "--skip-comments --skip-triggers " + db);
            run = Runtime.getRuntime().exec(Mysqlpath + "mysqldump --host=" + host + " --port=" + port + " --user=" + user + " --password=" + password + "  " + "--skip-comments --skip-triggers " + db);
        } catch (IOException ex) {
        }
        InputStream in = run.getInputStream();
        BufferedReader br = new BufferedReader(new InputStreamReader(in));
        StringBuffer temp = new StringBuffer();
        int count;
        char[] cbuf = new char[BUFFER];
        try {
            while ((count = br.read(cbuf, 0, BUFFER)) != -1) {
                temp.append(cbuf, 0, count);
            }
        } catch (IOException ex) {
        }
        try {
            br.close();
            in.close();
        } catch (IOException ex) {
        }
        return temp.toString();
    }

// Mysql path is required to locate the bin folder inside it because it contains the Mysqldump which performs a //main role while taking backup.
/*Function to find MySql Path*/
    public  String getMysqlBinPath(String dbUser, String dbPassword, String databaseName) {
        try {
            Class.forName("com.mysql.jdbc.Driver");
        } catch (Exception e) {
            e.printStackTrace();
            System.out.print("driver loading failed");
        }
        try {
            con = DriverManager.getConnection("jdbc:mysql://localhost:3306/" + databaseName, dbUser, dbPassword);
            st = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
        } catch (Exception e) {
            System.out.print("connection error");
            e.printStackTrace();
        }
        String a = "";
    try {
            rs = st.executeQuery("select @@basedir");
            while (rs.next()) {
                a = rs.getString(1);
            }
        } catch (Exception eee) {
            eee.printStackTrace();
        }
        a = a + "bin\\";
        System.err.println("Mysql path is :" + a);
        return a;
    }

}

1 comment:

  1. How to make a 3-in-4 - TITanium Entertainment
    Your main ford edge titanium for sale objective is titanium trimmer to achieve your vision, as much as titanium knee replacement you can. These are the three things you can do to create an experience is titanium a metal that t fal titanium pan can

    ReplyDelete