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







46 comments:

  1. hi
    can u send me full source code and how can restore this backup ??

    ReplyDelete
  2. Dear friend i tried to do this coding, but got several errors, this is very important programe. thanks for developing this. pls be kind to send me the netbeans project. ishan1211@gmail.com


    thanks.

    ReplyDelete
    Replies
    1. this code works perfectly....

      Delete
  3. hi,

    Thanks for the post...very nice..

    ReplyDelete
  4. hi
    can u send me full source code and how can restore this backup ??

    mnmfarhan@gmail.com

    thank u very much.

    ReplyDelete
  5. hello,
    could send me the complete project in douglasfabiano@gmail.com?

    Thank you and congratulations for example.

    ReplyDelete
  6. me puede mandar el proyecto amigo??? joseph_6108@hotmail.com

    ReplyDelete
  7. can u send me this source code, with frame
    email me at moriarty619@gmail.com

    ReplyDelete
  8. hi,,, it's helpful but I'm newbie ,would you send me full code to my email

    bagol.dunk@gmail.com

    ReplyDelete
  9. Hi bagol I have sent code to u... please check

    ReplyDelete
    Replies
    1. thank you very much sir,,, if I have any problems I will shall immediately notify you.

      Delete
  10. The use of File.separator , will make it also platform indipendent.
    Do you have something similar for the restoration of the database?
    Thanks once more!

    ReplyDelete
  11. Hello,
    I worked with your code and works fine.
    Do you have something for the opposite, restore the database?
    Thank you!

    ReplyDelete
  12. Good day I am so thrilled I found your website, I really found you
    by accident, while I was searching on Askjeeve for something else,
    Anyways I am here now and would just like to say thank
    you for a incredible post and a all round thrilling blog (I also love the theme/design), I don't have time to read through it all at the minute but I have saved it and also added in your RSS feeds, so when I have time I will be back to read a great deal more, Please do keep up the great work.
    my web page: mac online backup

    ReplyDelete
  13. hello friend,
    i tried to do this coding but got several errors, pls be kind to send me the netbeans project. data backup & restore .Thank you very much

    gdps90@gmail.com

    ReplyDelete
  14. hi
    can u send me full source code and how can restore this backup ??
    my email id is : riyakp@ymail.com

    ReplyDelete
  15. please send me complete source code
    my email address is: waqaralishah1@gmail.com

    ReplyDelete
  16. nice article.. realy worth... thankyou... :) :) :) :)

    ReplyDelete
  17. Can you please send me the Netbeans Project file.
    Thank you.
    email: a@bcs.org

    ReplyDelete
  18. hi... can you help me to send your source code/project netbeans for backup and restore...thx
    email : bizzard87@gmail.com

    ReplyDelete
    Replies
    1. Hey I have sent code to you plz check it. thanks....

      Delete
    2. hi bro..where is the connection?

      Delete
  19. Hey Sandeep, Your coding skills are great men. its really cool having guy like u arround. Can you pls send me ur code? Fank
    agwarjames@gmail.com

    ReplyDelete
    Replies
    1. I have provided link to git repository.

      Check it here. https://github.com/svshar/myrepo/tree/master/restback

      Delete
  20. Thanks .... it worked

    ReplyDelete
  21. Hi, Can you send me the code on how to restore this back up ... at jdajalos@yahoo.com

    ReplyDelete
  22. Hi @Rain Kim, I have sent code for backup / restore
    Chears...

    ReplyDelete
  23. thanks for this can u plz send me a way to restore the back.
    to pubudutennakoon@gmail.com

    ReplyDelete
  24. please send me restore project nuwan077512@gmail.com

    ReplyDelete
  25. Please send me the restore project, my email is jungleboy92zack@gmail.com

    ReplyDelete
  26. Please send me the restore project, my email is jackson.mwaniki@gmail.com

    ReplyDelete
  27. hello friend, i see your post, and i'm very need your code to implement for my project, im still studied, i'm live in indonesia. and now im the final semester student
    please you can send me this source code? because i can't download it.
    please help me, thanks

    you can send to sabanakholik@yahoo.com
    i'll be waiting for it,

    ReplyDelete
  28. are using H2 for creating database?

    ReplyDelete
  29. please send me restore project dumithrathnayaka@gmail.com

    ReplyDelete
  30. please send me backup restore project tatngth@gmail.com

    ReplyDelete
  31. please send me backup and restore project with mysql
    my e-mail : tatngth@gmail.com

    ReplyDelete
  32. Mysql path is :/usr/bin\
    /usr/bin\
    /usr/bin\mysqldump --host=localhost --port=3306 --user=root --password=ubuntu123 --compact --complete-insert --extended-insert --skip-comments --skip-triggers test

    i get this error anyone can solve it?

    ReplyDelete
  33. dhavaljoshi43@yahoo.com

    send me here full source code.. i got the above error

    ReplyDelete
  34. thank you...
    this code help me lot much

    ReplyDelete
  35. thank you
    it works
    can you please sent me the restore code to me please
    mohammedshabeerkb@gmail.com

    ReplyDelete
  36. please send me the code for restore. brianjohn787@gmail.com

    ReplyDelete
  37. Man Titanium Ankle for Women Women - Titanium Art
    Buy Woman's Personal Sockets in titanium properties the Men's titanium white acrylic paint Clothing department tittanium at Titanium Arts titanium dioxide & Services! Browse titanium coating Men's Clothing department store's collection

    ReplyDelete