Friday, February 25, 2011

MySql database backup (Swing) java

How to take MYSQL database backup from java swings?

Hello friends,
Here i have given explaination about how to take backup of mysql database from java swings below example i have created with the help of NetBeans 6.1, we will describe this step bye step.
often you required to take backup of mysql databases from your swing application. You can use mysqldump to take Mysql backup here i have try to simplify it.

if you are using Net Beans IDE then this will be very easy.

Step 1. - create a jframe in swing as shown as following figure





Step2: write below code under event of choose button

choose menu is to select the folder where you wish to take your backup sql file.
I have achieved it by using JFileChooser component of swing.

 txtbackuppath.setText(getBackUpPath());

//getBackUpPath() function is as shown below.


  public static String getBackUpPath() {

         String backUpPath = "";
         JFileChooser fc = null;
         if (fc == null) {
                fc = new JFileChooser();
                fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
                fc.setAcceptAllFileFilterUsed(false);
        }
        int returnVal = fc.showDialog(null, "Open");
        if (returnVal == JFileChooser.APPROVE_OPTION) {
            File file = fc.getSelectedFile();
            backUpPath = file.getAbsolutePath();
        }
       return backUpPath;
}



Hello friends uptill now we have seen that how we got the path where we can store the backup file of mysql database.
//above function is used to get the back up path dynamically by using jFileChooser component.
Now to connect with MySql we have required parameters such as Username, Password and database
name whose backup have to be taken it all shown in above figure.

Now we will see directly the code which is required for backup purpose.
this code is written under the backup button which is shown in above figure.

Step3: write below code under event of backup button



   String backuppath=txtbackuppath.getText();
   String Database =txtdatabasename.getText();
   String Password =txtpassword.getText();
   String user=txtuser.getText();
   Backup b = new Backup();
   try
  {
       byte[] data = b.getData("localhost", "3306", user,   Password, Database).getBytes();
       File filedst = new File(backuppath+"\\"+Database+".zip");
       FileOutputStream dest = new FileOutputStream(filedst);
       ZipOutputStream zip = new ZipOutputStream(
       new BufferedOutputStream(dest));
       zip.setMethod(ZipOutputStream.DEFLATED);
       zip.setLevel(Deflater.BEST_COMPRESSION);
       zip.putNextEntry(new ZipEntry("data.sql"));
       zip.write(data);
       zip.close();
       dest.close();
      JOptionPane.showMessageDialog(null, "Back Up Successfully."+"\n"+"For Database: "+Database+"\n        "+"On Dated: ","Database BackUp Wizard",JOptionPane.INFORMATION_MESSAGE);
   }catch (Exception ex){
    JOptionPane.showMessageDialog(null, "Back Up Failed."+"\n"+"For Database: "+Database+"\n "+"On     Dated: ","Database BackUp Wizard",JOptionPane.INFORMATION_MESSAGE);
    ex.printStackTrace();
  }

Hello friend this is what the code which takes the database backup in zipped format. it requires one more class file whose code i have given below

//It will require a "BackUp.java" file.


BackUp.java

import java.io.BufferedReader;
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.util.logging.Level;
import java.util.logging.Logger;

public class Backup
{

    private static ResultSet res;
    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("yaha dekho");
        }
        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("I am here yaaar");
            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) {
            // Logger.getLogger(Backup.class.getName()).log(Level.SEVERE, null, 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) {
            Logger.getLogger(Backup.class.getName()).log(Level.SEVERE, null, ex);
        }
        try {
            br.close();
            in.close();
        } catch (IOException ex) {
            Logger.getLogger(Backup.class.getName()).log(Level.SEVERE, null, 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 user, String password, String db) {
        try {
            Class.forName("com.mysql.jdbc.Driver");
        } catch (Exception e) {
            e.printStackTrace();
            System.out.print("yaha dekho");
        }
        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("I am here yaaar");
            e.printStackTrace();
        }


        String a = "";

        try {
            res = st.executeQuery("select @@basedir");
            while (res.next()) {
                a = res.getString(1);
            }
        } catch (Exception eee) {
            eee.printStackTrace();
        }
        a = a + "bin\\";
        System.err.println("Mysql path is :" + a);
        return a;
    }
}








//Above project is done in Netbeans if any one wants it's full source code can contact to me or they can leave //comment.

Download Source Code from Github Click here to download







Wednesday, February 16, 2011

how to export jtable data to excel file

Hello friends,
following is the  function which helps to export tables data to the excel file.
exportTable()  function takes two parameter one is table and another one is the file name

eg. exportTable(table, new File("D:\tabledata.xls"));

public void exportTable(JTable table, File file) throws IOException {
            TableModel model = table.getModel();
            FileWriter out = new FileWriter(file);
            for(int i=0; i < model.getColumnCount(); i++) {
        out.write(model.getColumnName(i) + "\t");
            }
            out.write("\n");

            for(int i=0; i< model.getRowCount(); i++) {
        for(int j=0; j < model.getColumnCount(); j++) {
            out.write(model.getValueAt(i,j).toString()+"\t");
            }
            out.write("\n");
        }

        out.close();
        System.out.println("write out to: " + file);
}

If any queries and any suggestions regarding this please mention