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 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
//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
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 buttonname 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.
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
hi
ReplyDeletecan u send me full source code and how can restore this backup ??
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
ReplyDeletethanks.
this code works perfectly....
Deletehi,
ReplyDeleteThanks for the post...very nice..
hi
ReplyDeletecan u send me full source code and how can restore this backup ??
mnmfarhan@gmail.com
thank u very much.
hello,
ReplyDeletecould send me the complete project in douglasfabiano@gmail.com?
Thank you and congratulations for example.
me puede mandar el proyecto amigo??? joseph_6108@hotmail.com
ReplyDeletecan u send me this source code, with frame
ReplyDeleteemail me at moriarty619@gmail.com
hi,,, it's helpful but I'm newbie ,would you send me full code to my email
ReplyDeletebagol.dunk@gmail.com
Hi bagol I have sent code to u... please check
ReplyDeletethank you very much sir,,, if I have any problems I will shall immediately notify you.
DeleteGreat tutorial!Thank you!
ReplyDeleteThe use of File.separator , will make it also platform indipendent.
ReplyDeleteDo you have something similar for the restoration of the database?
Thanks once more!
Hello,
ReplyDeleteI worked with your code and works fine.
Do you have something for the opposite, restore the database?
Thank you!
Good day I am so thrilled I found your website, I really found you
ReplyDeleteby 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
hello friend,
ReplyDeletei 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
Hi sanathana sent code to you thanks...
Deletehi
ReplyDeletecan u send me full source code and how can restore this backup ??
my email id is : riyakp@ymail.com
please send me complete source code
ReplyDeletemy email address is: waqaralishah1@gmail.com
Hi Waqar,sent code to you Thanks...
Deletenice article.. realy worth... thankyou... :) :) :) :)
ReplyDeleteCan you please send me the Netbeans Project file.
ReplyDeleteThank you.
email: a@bcs.org
hi... can you help me to send your source code/project netbeans for backup and restore...thx
ReplyDeleteemail : bizzard87@gmail.com
Hey I have sent code to you plz check it. thanks....
Deletehi bro..where is the connection?
DeleteHey Sandeep, Your coding skills are great men. its really cool having guy like u arround. Can you pls send me ur code? Fank
ReplyDeleteagwarjames@gmail.com
I have provided link to git repository.
DeleteCheck it here. https://github.com/svshar/myrepo/tree/master/restback
Thanks .... it worked
ReplyDeleteHi, Can you send me the code on how to restore this back up ... at jdajalos@yahoo.com
ReplyDeleteHi @Rain Kim, I have sent code for backup / restore
ReplyDeleteChears...
thanks for this can u plz send me a way to restore the back.
ReplyDeleteto pubudutennakoon@gmail.com
please send me restore project nuwan077512@gmail.com
ReplyDeletePlease send me the restore project, my email is jungleboy92zack@gmail.com
ReplyDeletePlease send me the restore project, my email is jackson.mwaniki@gmail.com
ReplyDeletehello 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
ReplyDeleteplease 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,
are using H2 for creating database?
ReplyDeleteno It is MySQL
ReplyDeleteplease send me restore project dumithrathnayaka@gmail.com
ReplyDeleteplease send me backup restore project tatngth@gmail.com
ReplyDeleteplease send me backup and restore project with mysql
ReplyDeletemy e-mail : tatngth@gmail.com
Mysql path is :/usr/bin\
ReplyDelete/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?
dhavaljoshi43@yahoo.com
ReplyDeletesend me here full source code.. i got the above error
thank you...
ReplyDeletethis code help me lot much
thank you
ReplyDeleteit works
can you please sent me the restore code to me please
mohammedshabeerkb@gmail.com
please send me the code for restore. brianjohn787@gmail.com
ReplyDeleteMan Titanium Ankle for Women Women - Titanium Art
ReplyDeleteBuy 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