MySQL Database Backup & Restore Using Java – Omindu's Blog

background image

11/01/2019

MySQL Database Backup & Restore Using Java – Omindu's Blog

https://omindu.wordpress.com/2011/06/27/mysql-database-backup-restore-using-java/

1/35

Omindu's Blog

MySQL Database Backup & Restore Using Java

(https://omindu.files.wordpress.com/2011/06/java-mysql.jpg)

Hello Programmers !!

It’s been a while since I’ve written a blog post. Luckily I’m in a mood to write something at the moment. Today I
thought about posting something I’ve learnt recently. It’s about database backups and restores through java.

If anyone wants to backup or restore a database without going through all these troubles, you can simply use
MySQL GUI Tools Bundle (http://dev.mysql.com/downloads/gui-tools/5.0.html) freely distributed by the Oracle
Corporation.

Sometimes it is necessary to integrate a backup & restore system to an application we are developing. In my case it
was a java application. In this post I’m expecting to give you guys a rough idea about backing up and restoring
your MySQL database through a Java Application.

1. Creating A Backup

When we install MySQL open source database it provides us a client called

mysqldump for backup purposes.

Here we execute this

mysqldump command using the java Runtime.

Here’s a sample method to create a complete database backup including add, drop MySQL statements.

Omindu in Programming

June 27, 2011May 2, 2016

840 Words

background image

11/01/2019

MySQL Database Backup & Restore Using Java – Omindu's Blog

https://omindu.wordpress.com/2011/06/27/mysql-database-backup-restore-using-java/

2/35

Basically what we are doing here is similar executing the following command in the windows command line.

Here

-u, -p, -B, -r are options to indicate that we are inserting the database username, password,

database name and location to save the backup respectively. The

--add-drop-database  option is to create

a complete backup. It means that when we are restoring the backup file, if the database does not exist in that
particular database the restoring process itself create the database automatically.

If by any chance you want to create a backup without add, drop database command. You can use the following
command.

For multiple databases use

If you want to backup All the databases. You can use the command as follows.

Likewise you can create your backup according to the requirements. There are many other options that you can add
to your command. You can visit mysqldump Docs (http://dev.mysql.com/doc/refman/5.1/en/mysqldump.html) for
more options or simply type

mysqldump --help on the command line to view the options.

That’s the basic idea about backing up the database. Let’s see how we can do the restoring process through java.

2. Restoring A Backup

d + " --add-drop-database -B " + dbName + " -r " + path;

1

mysqldump -u Username -pPassword --add-drop-database -B databaseName -r

1

mysqldump -u Username -pPassword databaseName -r backupPath

1

mysqldump -u Username -pPassword --add-drop-database -B db1 db2 db3 -r b

1

mysqldump -u Username -pPassword --add-drop-database -A -r backupPath

background image

11/01/2019

MySQL Database Backup & Restore Using Java – Omindu's Blog

https://omindu.wordpress.com/2011/06/27/mysql-database-backup-restore-using-java/

3/35

I had hard time finding a working code for the restoring process. After making a few changes on the commands
I’ve found on the internet, I’ve manage to create a workable runtime command for the restore process.

Note: The following method is to restore a complete database backup (backup with add, drop database
command)

If the the backup doesn’t have the add, drop database, you can use the following method.

I have tested all the commands and the methods mentioned in this post and they worked fine in Windows
environment. That’s all about creating & restoring backups. Hope you guys learnt something new.
If you have any questions please post them as a comment & I’ll try my best to answer them. I’m backing up for
now then. See you guys with another post. Hopefully!

Update

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

public

boolean

restoreDB(String dbUserName, String dbPassword, String s

String[] executeCmd =

new

String[]{"mysql", "--u

Process runtimeProcess;

try

{

runtimeProcess = Runtime.getRuntime().exec(executeCmd);

int

processComplete = runtimeProcess.waitFor();

if

(processComplete ==

0

) {

System.out.println("Backup restored successfully&q

return

true

;

}

else

{

System.out.println("Could not restore the backup&q

}

}

catch

(Exception ex) {

ex.printStackTrace();

}

return

false

;

}

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

public

static

boolean

restoreDB(String dbName, String dbUserName, Strin

String[] executeCmd =

new

String[]{"mysql", "--u

Process runtimeProcess;

try

{

runtimeProcess = Runtime.getRuntime().exec(executeCmd);

int

processComplete = runtimeProcess.waitFor();

if

(processComplete ==

0

) {

System.out.println("Backup restored successfully&q

return

true

;

}

else

{

System.out.println("Could not restore the backup&q

}

}

catch

(Exception ex) {

ex.printStackTrace();

}

return

false

;

}

background image

11/01/2019

MySQL Database Backup & Restore Using Java – Omindu's Blog

https://omindu.wordpress.com/2011/06/27/mysql-database-backup-restore-using-java/

4/35

Make sure to add the path of your ‘MySQL bin folder’ to the path variable in ‘Windows Environment Variables’.

References:
http://sureshk37.wordpress.com/2009/09/07/mysql-backup-and-restore-using-java/
(http://sureshk37.wordpress.com/2009/09/07/mysql-backup-and-restore-using-java/)
http://forums.mysql.com (http://forums.mysql.com/)

Tagged:
Database Backup,
Database Restore,
JAVA,
MySQL

126 thoughts on “MySQL Database Backup & Restore
Using Java”

chy says:
July 14, 2011 at 17:58
how do i backup a single table pls

 Reply

Omindu says:
July 14, 2011 at 20:39
u can try like this

mysqldump -u Username -pPassword databaseName --tables tbl1 tbl2 -r

backupPath

 Reply

chy says:
July 20, 2011 at 20:58
package files;

import java.util.*;
import java.io.*;
public class tableBackup_1 {
public boolean tbBackup(String dbName, String tbName, String dbUserName, String dbPassword, String path)
{

String executeCmd = “mysqldump -u ” + dbUserName + ” -p” + dbPassword +””
+ dbName + “–tables” + tbName + ” -r ” + path;

Process runtimeProcess;
try {
runtimeProcess = Runtime.getRuntime().exec(executeCmd);
int processComplete = runtimeProcess.waitFor();

if (processComplete == 0) {
System.out.println(“Backup created successfully”);
return true;
} else {

background image

11/01/2019

MySQL Database Backup & Restore Using Java – Omindu's Blog

https://omindu.wordpress.com/2011/06/27/mysql-database-backup-restore-using-java/

5/35

System.out.println(“Could not create the backup”);
}
} catch (Exception ex) {
ex.printStackTrace();
}
return false;
}
public static void main(String[] args){
tableBackup_1 bb = new tableBackup_1();
bb.tbBackup(“nsetrans”,”price”, “root”, “sa”, “C:/New Folder/table.sql”);

}
}

******** not working pls. what am i doing wrong?

 Reply

Omindu says:
July 20, 2011 at 22:59
Replace your executeCmd with this:

String executeCmd = "mysqldump -u " + dbUserName + " -p" + dbPassword +

" "
+ dbName + " --tables " + tbName + " -r " + path;

And change your path like this:

"\"C:/New Folder/table.sql\""

when your folder name has a space, you should include the path within double quotations.
should work fine

 Reply

chy says:
July 21, 2011 at 14:41
thanks. it worked.
am really grateful.

 Reply
Vibhakar says:
February 21, 2012 at 03:57
Thanks Qmindu, Your code worked perfectly……..

 Reply
Temur says:
March 23, 2012 at 16:08
Thank you for answer, I have question,
in my computer problem with mysqldump
java.io.IOException: Cannot run program “mysqldump”: CreateProcess error=2, The system cannot find the
file specified

 Reply

Omindu says:
March 23, 2012 at 22:05
Check whether you have given the path to the dump file correctly. If it doesn’t solve your problem, post
your code here. I can check it for you if you like.

 Reply

background image

11/01/2019

MySQL Database Backup & Restore Using Java – Omindu's Blog

https://omindu.wordpress.com/2011/06/27/mysql-database-backup-restore-using-java/

6/35

Amit says:
March 26, 2012 at 00:29
how to restore it to another mysql server connected via lan

 Reply

Omindu says:
March 26, 2012 at 00:48
Follow this example:

String[] executeCmd = new String[]{"mysql", "--host=" + dbIP, "--user="

+ dbUserName, "--password=" + dbPassword, dbName,"-e", "source
"+source};

Replace ‘dbIP’ with the IP of your server (ex: 192.168.1.25). The username you’re using should have
privileges to access the database remotely.

 Reply

Amit says:
March 26, 2012 at 16:54
but i have to execute this code on the from remote pc right??
i am creating a backup of db in pc1 and from pc1 i wnt to restore it to pc2.
so what do i do??

Omindu says:
March 26, 2012 at 20:51
Assuming you are running the program in PC1 & the backup file is also in PC1. Give the IP of PC2 as
‘dbIP’.

Amit says:
March 27, 2012 at 00:16
Thanks for the clarification…
Appreciate your help..thank you

 Reply
Kandie says:
April 5, 2012 at 14:45
Got this problem on windows xp. what is the cause.

ERROR com.busytech.barba.exception.BarbaException – java.io.IOException: Cannot run program
“C:\Program”: CreateProcess error=2, The system cannot find the file specified
com.busytech.barba.exception.BarbaException: Cannot run program “C:\Program”: CreateProcess error=2, The
system cannot find the file specified
at
com.busytech.barba.persistence.BackUpAndRestoreDatabaseManager.getTableBackup(BackUpAndRestoreDat
abaseManager.java:52)
at com.busytech.barba.servlet.checkcash.CashSummaryServlet.processRequest(CashSummaryServlet.java:95)
at com.busytech.barba.servlet.checkcash.CashSummaryServlet.doPost(CashSummaryServlet.java:495)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:637)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)

background image

11/01/2019

MySQL Database Backup & Restore Using Java – Omindu's Blog

https://omindu.wordpress.com/2011/06/27/mysql-database-backup-restore-using-java/

7/35

at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:298)
at org.apache.coyote.http11.Http11AprProcessor.process(Http11AprProcessor.java:864)
at
org.apache.coyote.http11.Http11AprProtocol$Http11ConnectionHandler.process(Http11AprProtocol.java:579)
at org.apache.tomcat.util.net.AprEndpoint$Worker.run(AprEndpoint.java:1665)
at java.lang.Thread.run(Unknown Source)
java.io.IOException: Cannot run program “C:\Program”: CreateProcess error=2, The system cannot find the
file specified
at java.lang.ProcessBuilder.start(Unknown Source)
at java.lang.Runtime.exec(Unknown Source)
at java.lang.Runtime.exec(Unknown Source)
at java.lang.Runtime.exec(Unknown Source)
at
com.busytech.barba.persistence.BackUpAndRestoreDatabaseManager.getTableBackup(BackUpAndRestoreDat
abaseManager.java:30)
at com.busytech.barba.servlet.checkcash.CashSummaryServlet.processRequest(CashSummaryServlet.java:95)
at com.busytech.barba.servlet.checkcash.CashSummaryServlet.doPost(CashSummaryServlet.java:495)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:637)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:298)
at org.apache.coyote.http11.Http11AprProcessor.process(Http11AprProcessor.java:864)
at
org.apache.coyote.http11.Http11AprProtocol$Http11ConnectionHandler.process(Http11AprProtocol.java:579)
at org.apache.tomcat.util.net.AprEndpoint$Worker.run(AprEndpoint.java:1665)
at java.lang.Thread.run(Unknown Source)
Caused by: java.io.IOException: CreateProcess error=2, The system cannot find the file specified
at java.lang.ProcessImpl.create(Native Method)
at java.lang.ProcessImpl.(Unknown Source)
at java.lang.ProcessImpl.start(Unknown Source)
… 21 more
347156 [http-8080-4] ERROR com.busytech.barba.exception.BarbaException – java.io.IOException: Cannot
run program “C:\Program”: CreateProcess error=2, The system cannot find the file specified
com.busytech.barba.exception.BarbaException: Cannot run program “C:\Program”: CreateProcess error=2, The
system cannot find the file specified
at
com.busytech.barba.persistence.BackUpAndRestoreDatabaseManager.getTableBackup(BackUpAndRestoreDat
abaseManager.java:52)
at com.busytech.barba.servlet.checkcash.CashSummaryServlet.processRequest(CashSummaryServlet.java:95)
at com.busytech.barba.servlet.checkcash.CashSummaryServlet.doPost(CashSummaryServlet.java:495)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:637)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)

background image

11/01/2019

MySQL Database Backup & Restore Using Java – Omindu's Blog

https://omindu.wordpress.com/2011/06/27/mysql-database-backup-restore-using-java/

8/35

at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:298)
at org.apache.coyote.http11.Http11AprProcessor.process(Http11AprProcessor.java:864)
at
org.apache.coyote.http11.Http11AprProtocol$Http11ConnectionHandler.process(Http11AprProtocol.java:579)
at org.apache.tomcat.util.net.AprEndpoint$Worker.run(AprEndpoint.java:1665)
at java.lang.Thread.run(Unknown Source)

 Reply

Omindu says:
April 5, 2012 at 21:22
From the look at it, it may be an error with your backup file path. Usually a path is given as follows in case
you don’t know

"\"C:/New Folder/table.sql\""

If the problem still exist, put your Backup/Restore method as here. I’ll try my best to find the error.

 Reply

latifa says:
April 24, 2012 at 03:55
hello,
I tested this code on windows, but it doesn’t work
java.io.IOException: Cannot run program “mysqldump”: CreateProcess error=2
maybe because before executing mysqldump in the windows command line i have to specify it’s path
.Otherwise it worked perfectly on linux.
Can you tell me what is the problem!
sorry for my english :$ and thank you for this blog it’s really interesting

 Reply

Omindu says:
April 24, 2012 at 21:03
Does the backup file is created when you execute the command on the windows command line ?

 Reply

mac says:
June 20, 2012 at 04:44
String[] executeCmd = new String[]{“mysql”, “–user=” + dbUserName, “–password=” + dbPassword, “-e”,
“source “+”D:/backup.sql\””};

i need to get back up of all the data base.my back file is in D drive.i got the like this exeption.
java.io.IOException: Cannot run program “mysqldump”: CreateProcess error=2, The system cannot find the
file specified .
can you help me to solve that exception. thank you very much for your attention.

 Reply

Omindu says:
July 27, 2012 at 21:55
Sorry for taking so long to reply mac. There’s a small error in your ‘path’ from what I can see. Try
replacing the statement as follows

String[] executeCmd = new String[]{“mysql”, “–user=” + dbUserName, “–password=” + dbPassword,
“-e”, “source ” + “\”D:/backup.sql\””};

 Reply

background image

11/01/2019

MySQL Database Backup & Restore Using Java – Omindu's Blog

https://omindu.wordpress.com/2011/06/27/mysql-database-backup-restore-using-java/

9/35

Gangadhar says:
July 17, 2012 at 15:19
Thanks mate.

It worked like a charm.

 Reply
amr magdy says:
July 27, 2012 at 21:15
i develop my application test as you discuss as that :

Backup class that contain backup method :

public class Backup {

public Backup() {
}

public boolean setBackup(String username,String password,String dbName,String path){
try {
String backupCommand=”mysqldump -u root -p e*ce11enceg@te db1 -r \”D:/mine/backup.sql\””;
Process myProcess=Runtime.getRuntime().exec(backupCommand);
int processComplete = myProcess.waitFor();
if(processComplete==0){
System.out.println(“backup executed”);
return true;
}else{
System.out.println(“backup not executed”);
}

} catch (InterruptedException ex) {
Logger.getLogger(Backup.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(Backup.class.getName()).log(Level.SEVERE, null, ex);
}
return false;
}
}

Main method :

public static void main(String[] args) {
Backup backup=new Backup();
boolean setBackup = backup.setBackup(“root”, “e*ce11enceg@te”, “db1”,
“\”D:/mine/SQLBackup/db1.sql\””);
if(setBackup){
System.out.println(“success”);
}else{
System.out.println(“fail”);
}
}

But i have an error that :

background image

11/01/2019

MySQL Database Backup & Restore Using Java – Omindu's Blog

https://omindu.wordpress.com/2011/06/27/mysql-database-backup-restore-using-java/

10/35

Jul 27, 2012 5:37:43 PM backuptest.Backup setBackup
fail
SEVERE: null
java.io.IOException: Cannot run program “mysqldump”: CreateProcess error=2, The system cannot find the
file specified
at java.lang.ProcessBuilder.start(ProcessBuilder.java:1029)
at java.lang.Runtime.exec(Runtime.java:615)
at java.lang.Runtime.exec(Runtime.java:448)
at java.lang.Runtime.exec(Runtime.java:345)
at backuptest.Backup.setBackup(Backup.java:24)
at backuptest.BackupTest.main(BackupTest.java:18)
Caused by: java.io.IOException: CreateProcess error=2, The system cannot find the file specified
at java.lang.ProcessImpl.create(Native Method)
at java.lang.ProcessImpl.(ProcessImpl.java:189)
at java.lang.ProcessImpl.start(ProcessImpl.java:133)
at java.lang.ProcessBuilder.start(ProcessBuilder.java:1021)
… 5 more

i don’t know if there is some thing error that i make

 Reply

Omindu says:
July 27, 2012 at 21:48
Try replacing ‘backupCommand‘ String as following. There shouldn’t be a space after ‘-p‘

String backupCommand = "mysqldump -u root -pe*ce11enceg@te db1 -r

\”D:/mine/backup.sql\”";

Also make sure there is a folder ‘mine’ in Driver ‘D:’

 Reply

amr magdy says:
July 28, 2012 at 04:28
thanks omindu for your help , but i found the error and solve it that write the path of “mysqldump” as
that :

C:\\Program Files\\MySQL\\MySQL Server 5.5\\bin\\mysqldump.exe

that code couldn’t run until i write it

thanks for your help again

Omindu says:
July 28, 2012 at 09:03
Glad it worked. And thanks a lot for your information. Lots of folks were having a similar problem and
it never occurred to me that the problem might be with the mysql path.

Arun Ramachandra Upadhya says:
August 10, 2012 at 02:41
Hi, Really nice program. But when i run this in servlet program with tomcat 6 server in ubuntu 10.04 server, its
not working. What i have to do if i want run it from server ? i tried lot. it will work with simple program but not
in server. Please help.

 Reply

Omindu says:
October 19, 2012 at 20:07

background image

11/01/2019

MySQL Database Backup & Restore Using Java – Omindu's Blog

https://omindu.wordpress.com/2011/06/27/mysql-database-backup-restore-using-java/

11/35

Hello Arun,
Sorry for taking a long time to reply. I am not much familiar with servlet programs. I hope you found a
solution for your problem. Good Luck

 Reply

shruthi says:
August 11, 2012 at 20:52
can you please let me know how to fetch only the required fields from a table?

 Reply

Omindu says:
October 19, 2012 at 21:32
Hello Shruthi,
Sorry for taking too long to reply. I couldn’t find a direct way to create such a dump. May be you can create
a ‘view’ and create a dump for that view. I have never tried this though. But it might work Please leave a
comment if it works.

 Reply

vipin says:
August 16, 2012 at 12:46
Usefull

 Reply
Jitendra Yadav says:
October 15, 2012 at 12:01
Thanks for such precious post

 Reply
Dragan Mihajlovic says:
October 19, 2012 at 13:34
Hello, I have tried some of your code and it works fine. Thanks for that.
I wonder if there is a code for remote back up. In other words I want to back up database from remote
computer. I saw there is code for remote restore…

 Reply

Omindu says:
October 19, 2012 at 21:04
you can try something like this:

mysqldump -u Username -pPassword --add-drop-database -h hostIP -B

databaseName -r backupPath

Hope this help. Reply If you need a further clarification.

 Reply

Dragan Mihajlovic says:
October 24, 2012 at 16:47
Thanks… it works fine.
Just to pinpoint as to my current knowledge if I want to back up or restore database from remote
computer I think that i have to have MySQL server instaled on that remote computer in order that I can
use mysqldump..
…or not…?

pubudu says:
October 22, 2012 at 11:09

background image

11/01/2019

MySQL Database Backup & Restore Using Java – Omindu's Blog

https://omindu.wordpress.com/2011/06/27/mysql-database-backup-restore-using-java/

12/35

thanks for this.
i have a problem my back code works fine but wen i use the restore code it dosent work. i will post my code if
u can please help me.

public boolean restoreDB(String dbName, String dbUserName, String dbPassword, String source) {

String[] executeCmd = new String[]{“C:\\Program Files\\MySQL\\MySQL Server 5.5\\bin\\mysql.exe”, “–
user=” + dbUserName, “–password=” + dbPassword, dbName,”-e”, “source=”+source};

Process runtimeProcess;

try {

runtimeProcess = Runtime.getRuntime().exec(executeCmd);

int processComplete = runtimeProcess.waitFor();

if (processComplete == 0) {

System.out.println(“Backup restored successfully”);

return true;

} else {

System.out.println(“Could not restore the backup”);

}

}
catch (Exception e) {
JOptionPane.showMessageDialog(this, “”+e.getMessage()+” Error, !”,””,JOptionPane.OK_OPTION);
}

return false;

}

 Reply

Omindu says:
October 22, 2012 at 22:19
Hello Pubudu,
I think I have found the error. Replace your

executCmd as follows

String[] executeCmd = new String[]{"C:\\Program Files\\MySQL\\MySQL

Server 5.5\\bin\\mysql.exe", "--user=" + dbUserName, "--password=" +
dbPassword, dbName,"-e", "source "+source};

Note that there’s No ‘=’ after the ‘source’

Hope this helps.

 Reply

Anonymous says:
December 30, 2012 at 13:41
Omindu, thank you so much for this article, after more than one year this article still very very useful. I tried to
lot of codes before found your article, thanx very much again

background image

11/01/2019

MySQL Database Backup & Restore Using Java – Omindu's Blog

https://omindu.wordpress.com/2011/06/27/mysql-database-backup-restore-using-java/

13/35

eranga

 Reply
zia says:
January 4, 2013 at 15:48
java.io.IOException: Cannot run program “mysql”: CreateProcess error=2, The system cannot find the file
specified
at java.lang.ProcessBuilder.start(Unknown Source)
at java.lang.Runtime.exec(Unknown Source)
at java.lang.Runtime.exec(Unknown Source)
at com.nvl.admindao.restoreDB.restoreDB(restoreDB.java:19)
at com.nvl.admindao.restoreDB.main(restoreDB.java:53)
Caused by: java.io.IOException: CreateProcess error=2, The system cannot find the file specified
at java.lang.ProcessImpl.create(Native Method)
at java.lang.ProcessImpl.(Unknown Source)
at java.lang.ProcessImpl.start(Unknown Source)
… 5 more
Data is restored unsuccessfully

Please Note: – your code shows above exceptions

 Reply
Anonymous says:
January 10, 2013 at 10:43
I m able to take the database backup and zip it.
but i m not able to restore the same file

 Reply
Isuru Ranawaka says:
January 14, 2013 at 08:11
NIce thread of comments. I find the command line utility not useful when the path is not set to the MySQL bin
folder. So I created a solution using simple JDBC statements. here it is. Hope it will useful to someone here.

ResultSet rs = query(“SHOW FULL TABLES WHERE Table_type != ‘VIEW'”);
while (rs.next()) {
String tbl = rs.getString(1);

sb.append(“\n”);
sb.append(“– —————————-\n”)
.append(“– Table structure for `”).append(tbl)
.append(“`\n– —————————-\n”);
sb.append(“DROP TABLE IF EXISTS `”).append(tbl).append(“`;\n”);
ResultSet rs2 = query(“SHOW CREATE TABLE `” + tbl + “`”);
rs2.next();
String crt = rs2.getString(2) + “;”;
sb.append(crt).append(“\n”);
sb.append(“\n”);
sb.append(“– —————————-\n”).append(“– Records for `”).append(tbl).append(“`\n–
—————————-\n”);

ResultSet rss = query(“SELECT * FROM ” + tbl);
while (rss.next()) {
int colCount = rss.getMetaData().getColumnCount();
if (colCount > 0) {
sb.append(“INSERT INTO “).append(tbl).append(” VALUES(“);

background image

11/01/2019

MySQL Database Backup & Restore Using Java – Omindu's Blog

https://omindu.wordpress.com/2011/06/27/mysql-database-backup-restore-using-java/

14/35

for (int i = 0; i 0) {
sb.append(“,”);
}
String s = “”;
try {
s += “‘”;
s += rss.getObject(i + 1).toString();
s += “‘”;
} catch (Exception e) {
s = “NULL”;
}
sb.append(s);
}
sb.append(“);\n”);
buff.append(sb.toString());
sb = new StringBuilder();
}
}
}

ResultSet rs2 = query(“SHOW FULL TABLES WHERE Table_type = ‘VIEW'”);
while (rs2.next()) {
String tbl = rs2.getString(1);

sb.append(“\n”);
sb.append(“– —————————-\n”)
.append(“– View structure for `”).append(tbl)
.append(“`\n– —————————-\n”);
sb.append(“DROP VIEW IF EXISTS `”).append(tbl).append(“`;\n”);
ResultSet rs3 = query(“SHOW CREATE VIEW `” + tbl + “`”);
rs3.next();
String crt = rs3.getString(2) + “;”;
sb.append(crt).append(“\n”);
}

buff.flush();
buff.close();
} catch (Exception e) {
e.printStackTrace();
}
}

Full resource is at http://isuru.diyatha.com/java-db-dump/.

 Reply
Pingback: Criando dump do MySQL com java no Linux | Cláudio HMB – Developer
Синиша Бубоња says:
February 14, 2013 at 00:45
Great! Thanx!!!

 Reply
Anonymous says:
February 22, 2013 at 23:29
Excellent!! was of great help to me. : D Thanks!!!!!!

background image

11/01/2019

MySQL Database Backup & Restore Using Java – Omindu's Blog

https://omindu.wordpress.com/2011/06/27/mysql-database-backup-restore-using-java/

15/35

 Reply
Anonymous says:
March 20, 2013 at 15:19
thanks .I study backup & restore

 Reply
thamara says:
March 31, 2013 at 13:02
You are a genius. Thank you very much for your code relating backups.

 Reply
Anonymous says:
May 2, 2013 at 03:20
fine work thanks alot after a long chase i finally able to restore me database thanks again

 Reply
jorges says:
June 11, 2013 at 20:35
HI Dude,
i’m try to do a backup of my database but my code not work,i have some error.
this is the code
public boolean tbBackup(String dbName, String dbUserName, String dbPassword, String path) {

String[] executeCmd = new String []{ “mysqldump -u ” + dbUserName + ” -p ” + dbPassword + ” –add-drop-
database -B ” + dbName + ” -r ” +path};

Process runtimeProcess;
try {
runtimeProcess = Runtime.getRuntime().exec(executeCmd);

int processComplete = runtimeProcess.waitFor();
if(processComplete == 0)
{
System.out.println(“Backup Réalisé avec Success”);
return true;
}else{

System.out.println(“Impossible de Réaliser le Backup Système!!!”);
}
} catch (Exception e) {
e.printStackTrace();
// TODO: handle exception
}

public static void main(String[] args) {
BackupRestor backupRestor = new BackupRestor();
backupRestor.tbBackup(“chantier”, “root”, “”, “\”C:/Torrent Stream/table.sql\””);

}

The are is:

java.io.IOException: CreateProcess: “mysqldump -u root -p –add-drop-database -B chantier -r “C:\Torrent
Stream\table.sql”” error=2
at java.lang.ProcessImpl.create(Native Method)
at java.lang.ProcessImpl.(ProcessImpl.java:81)

background image

11/01/2019

MySQL Database Backup & Restore Using Java – Omindu's Blog

https://omindu.wordpress.com/2011/06/27/mysql-database-backup-restore-using-java/

16/35

at java.lang.ProcessImpl.start(ProcessImpl.java:30)
at java.lang.ProcessBuilder.start(ProcessBuilder.java:451)
at java.lang.Runtime.exec(Runtime.java:591)

Please help me,Thank

 Reply

Omindu says:
June 11, 2013 at 21:22
Try replacing “

String[] executeCmd ” with:

String executeCmd = "mysqldump -u " + dbUserName + " -p" + dbPassword +

" --add-drop-database -B " + dbName + " -r " + path;

 Reply

Gaganbv says:
June 24, 2013 at 16:09
public class tableBackup_1 {
public boolean tbBackup() {

String[] Cmd = new String[]{“C:\\wamp\\bin\\mysql\\mysql5.0.51b\\bin” , “mysqldump -u root -p nepldb -r
D:\\backup\\db_backup” };

Process runtimeProcess;
try {
runtimeProcess = Runtime.getRuntime().exec(Cmd);
int processComplete = runtimeProcess.waitFor();

if (processComplete == 0) {
System.out.println(“Backup created successfully”);
return true;
} else {
System.out.println(“Could not create the backup”);
}
} catch (Exception ex) {
ex.printStackTrace();
}
return false;
}
}

java.lang.NoSuchMethodError: main
Exception in thread “main”

 Reply

Gaganbv says:
June 24, 2013 at 16:10
could you help me out with the error?!?

 Reply

Omindu says:
June 24, 2013 at 19:18
Have you declared your main() correctly?

public static void main(String[] args) {

new tableBackup_1().tbBackup();
}

background image

11/01/2019

MySQL Database Backup & Restore Using Java – Omindu's Blog

https://omindu.wordpress.com/2011/06/27/mysql-database-backup-restore-using-java/

17/35

Usually this error occurs when there’s an error with the main() declaration.

tushar gawas says:
July 30, 2013 at 00:20
Hi, m trying to restore database file. But I am unable to do. Following is my code.

package restore;

public class Restore{

public static boolean restoreDB(String source) {

String dbUserName= “root”;
String dbPassword=””;
String dbName=”tushar”;
String[] executeCmd = new String[]{“C:\\xampp\\mysql\\bin\\mysql”, “–user=” + dbUserName, “–password=”
+ dbPassword, dbName,”-e”, “source “+source};

Process runtimeProcess;
try {

runtimeProcess = Runtime.getRuntime().exec(executeCmd);
int processComplete = runtimeProcess.waitFor();
System.out.println(“processComplete “+processComplete);
if (processComplete == 0) {
System.out.println(“Backup restored successfully”);
return true;
} else {
System.out.println(“Could not restore the backup”);
}
} catch (Exception ex) {
ex.printStackTrace();
}

return false;
}

public static void main(String[]args){

new Restore().restoreDB(“C:/Users/Tushar/Downloads/tushar.sql”);
}

}

Output:
processComplete 1
Could not restore the backup

Plz Help.
Thanks in advance.

 Reply

Omindu says:
August 22, 2013 at 21:41

background image

11/01/2019

MySQL Database Backup & Restore Using Java – Omindu's Blog

https://omindu.wordpress.com/2011/06/27/mysql-database-backup-restore-using-java/

18/35

Sorry for replying so late Tushar. Try using this line. It’s working fine in my PC.

executeCmd = new String[]{"C:\\xampp\\mysql\\bin\\mysql", "--user=" +

dbUserName, "--password=" + dbPassword, dbName,"-e", "source "+source};

 Reply

TY says:
August 6, 2013 at 20:22
Many Thanks Friend

 Reply
NitinS says:
August 8, 2013 at 14:57
An complete working example on how to use these commands from JSP code can be found here
http://www.jvmhost.com/articles/mysql-postgresql-dump-restore-java-jsp-code

 Reply
volodiaL says:
August 14, 2013 at 22:06
Hello!

Thanks for this post.

I only copied your method backupDB.
Indeed this method is running for me but unfotunately forever. It does not want to stop and red icon in eclipse
console says about it. I think the problem is in method waitFor but if I substitute it with exitValue I reeive
exception
java.lang.IllegalThreadStateException: process has not exited
So I must use waitFor method.
Couldn’t you tell me what may cause waitFor method to run forever?

Thanks!

 Reply

Omindu says:
August 22, 2013 at 21:09
Sorry volodiaL. I can’t think of anything that might be causing the error. I have never encountered that error
while working with the code. Hope you’ll manage to find a solution.

 Reply

Nizar says:
August 22, 2013 at 02:41
Could help me please?
my program :
String database=”db1″;
String user=”root”;
String pass=””;
String path=”D:\\table.sql”;
String path1=”C:\\Program Files\\EasyPHP5\\mysql\\bin\\mysqldump.exe”;

String dumpCommand =path1+” –database ” + database + ” -u ” + user +” -r ” + path;

String executeCmd = path1 + ” -u ” + user +” -p ” + pass + database + ” -r ” + path;
Process runtimeProcess;
try {

background image

11/01/2019

MySQL Database Backup & Restore Using Java – Omindu's Blog

https://omindu.wordpress.com/2011/06/27/mysql-database-backup-restore-using-java/

19/35

runtimeProcess = Runtime.getRuntime().exec(dumpCommand);
int processComplete = runtimeProcess.waitFor();

if (processComplete == 0) {
System.out.println(“Backup created successfully”);

} else {
System.out.println(processComplete+” Could not create the backup”);
}
} catch (Exception ex) {
ex.printStackTrace();
and my program dosen’t create my file and it display: 2 could not create.
thanks

 Reply

Omindu says:
August 22, 2013 at 21:02
Try changing

dumpCommand to

dumpCommand = path1+" -u "+user+" -p"+pass+" "+database+" -r"+path

 Reply

Kannan says:
August 28, 2013 at 11:14
Pls Help me………

My Program:

class Backup {

public boolean backupDB() {
String user = “root”;
String pass = “password”;
String db = “school”;
String path = “\”E:/DBbackp/backup.%DATE:~10,4%%DATE:~7,2%%DATE:~4,2%.sql\””;
//System.out.println(“”);
//System.out.println(“Could not create the backup”);
//System.out.println(“Could not create the backup”);
//System.out.println(“Could not create the backup”);

String executeCmd = “mysqldump -u ” + user + ” -p” + pass + ” –add-drop-database -B ” + db + ” -r ” + path;

Process runtimeProcess;
try {

runtimeProcess = Runtime.getRuntime().exec(executeCmd);
int processComplete = runtimeProcess.waitFor();

if (processComplete == 0) {
System.out.println(“Backup created successfully”);
return true;
} else {
// Runtime.getRuntime().exec(“mysql-backup.bat”);
System.out.println(“Could not create the backup”);
}

background image

11/01/2019

MySQL Database Backup & Restore Using Java – Omindu's Blog

https://omindu.wordpress.com/2011/06/27/mysql-database-backup-restore-using-java/

20/35

} catch (Exception ex) {
ex.printStackTrace();
}

return false;
}
}

Output:
Could not create the backup

pls help…

Thanks in Advance.,

 Reply

Omindu says:
August 28, 2013 at 22:11
Try changing the file name to a simpler one. It should work.

 Reply
shan says:
September 11, 2013 at 11:22
If you want to name your sql file in the date or time, I’d suggest you to auto generate it using LocalDate in
JodaTime package.

 Reply

Eukaliptus says:
August 28, 2013 at 15:02
Both options that you write for restoring the database are equal. I found my own solution using a comand like
this:
“cmd.exe /C ” + “C:\\wamp\\bin\\mysql\\mysql5.6.12\\bin\\mysql –user=” + Username + ” –password=” +
Password + ” –default-character-set=utf8 –comments” + ” < " + Path ;

I hope it will help somebody.
Doing it like this mysql is able to read some of the lines inside the .sql that are encoded in a different way.
Good luck!

 Reply

Omindu says:
August 28, 2013 at 22:10
Thanks for the reply. Hope this will be useful.

 Reply

sumit says:
September 11, 2013 at 03:17
Backing up process is taking too much time which is making my web app hang but when i used same code in
cmd prompt it backs up in a sec what might be the problme any idea?

 Reply

Omindu says:
September 11, 2013 at 22:10
I’m sorry but can’t think of any reason.

 Reply
shan says:

background image

11/01/2019

MySQL Database Backup & Restore Using Java – Omindu's Blog

https://omindu.wordpress.com/2011/06/27/mysql-database-backup-restore-using-java/

21/35

September 12, 2013 at 10:07
I had the same problem and this is how I solved, my code goes like this…

////////////////////////////////////////////////////////////////////////////////////////////////////////////
String executeCmd = “your mysqldump or mysql command”;

Process runtimeProcess = Runtime.getRuntime().exec(executeCmd);
InputStream is = runtimeProcess.getInputStream();

int byteRead = -1;
while ((byteRead = is.read()) != -1) {
System.out.print((char)byteRead );
}

int processComplete = runtimeProcess.waitFor();
if (processComplete == 0) {

// this is when the backing up is done successfully.
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////

hope this helps… good luck

 Reply

shan says:
September 11, 2013 at 11:17
Thanks Omindu!
I refered this code and used. Great.
But restoring a db is taking lots of time. So I searched for a solution. And I found this
http://stackoverflow.com/questions/13227057/importing-mysql-database-from-java-code

I think “apache commons Utils”-“Exec” is the best solution.

 Reply

Omindu says:
September 11, 2013 at 22:04
Thanks for the information shan.

 Reply

Atul Vairale says:
September 17, 2013 at 17:42
I am using external MySQL server means not installed MySQL server in PC for my desktop application now i
want export and import database from server present in E folder.your code running perfectly for installed
MySQL server. I am using following path but it does not work.
String executeCmd = ” mysqldump -u ” + dbUserName + ” -p” + dbPassword + ” –add-drop-database -B ” +
dbName + ” -r ” + path;

 Reply

Amit Ranjan says:
September 19, 2013 at 11:49
please post both your code and what are u getting error……..

 Reply

Atul Vairale says:
October 3, 2013 at 16:26
This is my BackUp function

background image

11/01/2019

MySQL Database Backup & Restore Using Java – Omindu's Blog

https://omindu.wordpress.com/2011/06/27/mysql-database-backup-restore-using-java/

22/35

public static boolean backupDB(String dbName, String dbUserName, String dbPassword, String path) {
String executeCmd = “mysqldump.exe -u ” + dbUserName + ” -p ” + dbPassword + ” –add-drop-
database -B ” + dbName + ” -r ” + path;
Process runtimeProcess;
try {
runtimeProcess = Runtime.getRuntime().exec(executeCmd);
int processComplete = runtimeProcess.waitFor();

if (processComplete == 0) {
System.out.println(“Backup created successfully”);
return true;
} else {
System.out.println(“Could not create the backup”);
}
} catch (Exception ex) {
ex.printStackTrace();
}
return false;
}

With this empty sql file is created.

Omindu says:
October 25, 2013 at 19:09
I’m not sure what’s causing the error. Can you try replacing your executeCmd exactly as follows.

"mysqldump.exe -u " + dbUserName + " -p" + dbPassword + " --add-

drop-database -B " + dbName + " -r " + path;

Atul Vairale says:
October 26, 2013 at 19:28
I am not using MySQL installed on computer.I create process which start specified MySQL by following
code

StartMysqlServer.p = Runtime.getRuntime().exec(“server/bin/mysqld –defaults-file=server/my.ini –
standalone –console –basedir=server/”);

I want database Import,Export present in this started MySQL server.

 Reply

Atul Vairale says:
October 29, 2013 at 11:27
Thanks to omindu,Amit ranjan. I have solved problem.Before this Mysql server has no password now i
set password and run then i got back up of database suceesfully.

Atul Vairale says:
October 29, 2013 at 18:03
I exported database successfully but when i import that then i get message backup successfully
restore.when i see database then it is empty but when i use another sql file created by cmd then restore
successfully and there is data in database.so i think problem in my export i used following code public static
boolean backupDB(String dbName, String dbUserName, String dbPassword, String path) {
Process runtimeProcess;
String executeCmd=”mysqldump -d -u ” + dbUserName + ” -p” + dbPassword + ” –add-drop-database -B ”
+ dbName + ” -r ” + path;

background image

11/01/2019

MySQL Database Backup & Restore Using Java – Omindu's Blog

https://omindu.wordpress.com/2011/06/27/mysql-database-backup-restore-using-java/

23/35

try {
runtimeProcess = Runtime.getRuntime().exec(executeCmd);
int processComplete = runtimeProcess.waitFor();

if (processComplete == 0) {
System.out.println(“Backup created successfully”);
return true;
} else {
System.out.println(“Could not create the backup”);
}
} catch (Exception ex) {
ex.printStackTrace();
}
return false;
}

 Reply
Atul Vairale says:
November 11, 2013 at 18:42
I have another query if i used MySQL Server present at path D:/Copies/10-10-2013/server – Copy (2)/bin>
then how i run dump command on this path means i want import/export databases present in mentioned
path Server.

 Reply

Omindu says:
November 11, 2013 at 23:42
You can use something like this,

String[] executeCmd = new String[]{"D:\\Copies\\10-10-2013\\server –

Copy (2\\bin\\mysql.exe", "--user=" + dbUserName, "--password=" +
dbPassword, dbName,"-e", "source "+source};

Atul Vairale says:
December 3, 2013 at 09:53
It is working.Thank you very much…

jeff says:
September 18, 2013 at 12:42
Hi…Can I have a whole java program that includes back-up for MySQL database!

 Reply
Amit Ranjan says:
September 18, 2013 at 16:39
my backup java program is successfully compile and run……..but output is not able to satisfied. database have
table.

output is :could not create the backup

please help me

 Reply
Amit Ranjan says:
September 19, 2013 at 11:47
Please help

background image

11/01/2019

MySQL Database Backup & Restore Using Java – Omindu's Blog

https://omindu.wordpress.com/2011/06/27/mysql-database-backup-restore-using-java/

24/35

my backup java program is successfully compile and run……..but output is not import java.util.*;
import java.sql.*;
public class DbbackUp
{
public boolean backupDB(String dbName,String dbUserName,String dbPassword, String path)
{
String executeCmd =”mysqldump -u” + dbUserName + ” -p” + dbPassword + ” databaseName ” + dbName + ”
-r ” +path;
Process runtimeProcess;
try {

//runtimeProcess = Runtime.getRuntime().exec(executeCmd);
runtimeProcess=Runtime.getRuntime().exec(new String[] { “cmd.exe”, “/c”, executeCmd });
int processComplete = runtimeProcess.waitFor();

if (processComplete == 0) {
System.out.println(“Backup created successfully”);
return true;
} else {
System.out.println(“Could not create the backup”);
}
} catch (Exception ex) {
ex.printStackTrace();
}

return false;
}
public static void main(String args[])
{
DbbackUp db=new DbbackUp();
db.backupDB(“root”,”12345″,”test”,”\”C:/New Folder/employeewe.sql\””);
}
}

output: Could not create the backup.

i had changed the file name to a similar but still i am getting same output
please help me

 Reply

Shan J. says:
September 24, 2013 at 03:59
Hello Amit,
Please add these lines on the top of your “try block ”

////////////////////////////////////////////////////////////////////////////////////////
InputStream is = runtimeProcess.getInputStream();

int byteRead = -1;
while ((byteRead = is.read()) != -1) {
System.out.print((char)byteRead );
}
////////////////////////////////////////////////////////////////////////////////////////

And check the output.

background image

11/01/2019

MySQL Database Backup & Restore Using Java – Omindu's Blog

https://omindu.wordpress.com/2011/06/27/mysql-database-backup-restore-using-java/

25/35

 Reply

Amit Ranjan says:
October 25, 2013 at 10:52
still i am getting error.

Omindu says:
October 25, 2013 at 19:41
Noticed a few errors in your runtime execution. Try the following,

String executeCmd = "mysqldump -u " + dbUserName + " -p" + dbPassword
+ " " + dbName + " -r " + path;

Also check whether you are passing the correct arguments for your backupDB function.
Looks to me that you have mistakenly swapped the database and username values.

One more thing, sometimes windows doesn’t allow you to write files to the windows partition if you are
not running your IDE as an administrator. Try saving the file in a different partition.

Anonymous says:
October 3, 2013 at 16:18
I have same issue

 Reply
Atul Vairale says:
October 3, 2013 at 16:27
I have a same problem..

 Reply

zitkom says:
September 23, 2013 at 18:01
Legend…

 Reply
Elmore says:
October 24, 2013 at 10:30
Hi Omindu,

I’ve followed your code with minor modifications but my program could not complete the backup process.
Here’s my code:

public int backupDb()
{
String executeCmd = “\”C:\\Program Files\\MySQL\\MySQL Server 5.6\\bin\\mysqldump\” –add-drop-
database –add-drop-table -h localhost -u=root -p=root -r c:\\backup\\backup.sql –dump-date –databases
salondb”;
Process runtimeProcess;
try
{
runtimeProcess = Runtime.getRuntime().exec(executeCmd);
int processComplete = runtimeProcess.waitFor();
if (processComplete != 0)
return 1; // backup failed
}
catch (Exception ex)

background image

11/01/2019

MySQL Database Backup & Restore Using Java – Omindu's Blog

https://omindu.wordpress.com/2011/06/27/mysql-database-backup-restore-using-java/

26/35

{
ex.printStackTrace();
}

// backup successful
return 0;
}

The backup file is created in folder C:\backup but it does not contain anything, as in 0 bytes file size. I tried
running the command in a command window and got this error:

mysqldump: Got error: 1045: Access denied for user ‘=root’@’localhost’ (usi
ng password: YES) when trying to connect.

I’m already using root for crying out loud! Double-checked root’s permission and roles, everything’s allowed
on any database.

Any ideas why this is? I use Windows 7, Glassfish 4.0.1 and MySQL v5.6.14. Thank you in advance.

 Reply

Omindu says:
October 24, 2013 at 19:08
Got the same problem when I ran your code. Use -u root -proot instead of what you are using. It’ll work

 Reply

Atul Vairale says:
October 29, 2013 at 15:59
I have query, I export database successfully now i want to export a database but some tables with data and
remaining tables should be empty.Is this possible?

 Reply
Yash says:
November 16, 2013 at 18:24
It’s not working here …

executeCmd =”mysqldump -u root –all-databases > G:\\dump.sql”;

It Simply Prints :- Could not create the backup

 Reply
shartani says:
January 27, 2014 at 16:24
hey…i am getting a problem while taking backup from remote mysqlserver…i followed ur code and
instruction..its working on local machine but not on remote..

plz reply if u can help..

public class back
{
public static void main(String args[])
{
Process p = null;
try {
Runtime runtime = Runtime.getRuntime();

background image

11/01/2019

MySQL Database Backup & Restore Using Java – Omindu's Blog

https://omindu.wordpress.com/2011/06/27/mysql-database-backup-restore-using-java/

27/35

p = runtime.exec(“C:/Program Files (x86)/MySQL/MySQL Server 5.0/bin/mysqldump -h remotehostip -u root
-ppassword –add-drop-database -B dbname -r D:\\abc.sql”);
int processComplete = p.waitFor();

if (processComplete == 0) {

System.out.println(“Backup created successfully!”);

} else {
System.out.println(“Could not create the backup”);
}

} catch (Exception e) {
e.printStackTrace();
}
}
}

output is : could not create backup…

 Reply
Kavinda Inusha says:
February 27, 2014 at 22:35
this code not worked on windows 8..it says cannot find path..what should i do now ?..
here is my code example –>>>

try {
//
File file = new File(“C://AgencyBackup”);
if (!file.exists()) {
file.mkdir();
}

String path = file.getAbsolutePath() + “/” + new SimpleDateFormat(“yyyy-MM-dd_hh.mm a”).format(new
Date()) + “.sql”;

String execute = ” -u ” + “root” + ” -p” + “123” + ” –add-drop-database -B ” + “agent” + ” -r ” + path;
Process proccess = Runtime.getRuntime().exec(“C:/Program Files (x86)/MySQL/MySQL Server
5.1//bin/mysqldump” + execute.trim());
int success = proccess.waitFor();

if (success == 0) {
JOptionPane.showMessageDialog(null, “Backup Credted Successfully.”, “SUCCESS MESSAGE MESSAGE”,
JOptionPane.INFORMATION_MESSAGE);

} else {
JOptionPane.showMessageDialog(null, “Could Not Create The Backup”, “ERROR MESSAGE”,
JOptionPane.ERROR_MESSAGE);
}
} catch (IOException ex) {
model.writeLog(ex);
ex.printStackTrace();
JOptionPane.showMessageDialog(null, “File : ” + ex.getMessage(), “ERROR MESSAGE”,
JOptionPane.ERROR_MESSAGE);
} catch (InterruptedException ex) {
model.writeLog(ex);

background image

11/01/2019

MySQL Database Backup & Restore Using Java – Omindu's Blog

https://omindu.wordpress.com/2011/06/27/mysql-database-backup-restore-using-java/

28/35

ex.printStackTrace();
JOptionPane.showMessageDialog(null, “Backup : ” + ex.getMessage(), “ERROR MESSAGE”,
JOptionPane.ERROR_MESSAGE);
}

 Reply
Anonymous says:
March 1, 2014 at 17:50
Your post was really useful, Thank you!!

 Reply
Marcos says:
March 1, 2014 at 17:52
I was using the following instead of using String[], but it didn’t work and took forever to run the restore. Just
wondering why?

 Reply
Marcos says:
March 1, 2014 at 17:53
String executeCmd = “mysql -u ” + dbUserName + ” -p” + dbPassword + ” ” + dbName + ” < " + source;

 Reply
anto says:
May 6, 2014 at 15:44
how can restore mysql database from my pc to remote server database using java code

 Reply

Omindu says:
May 6, 2014 at 16:23
Check the following. It might help.
https://omindu.wordpress.com/2011/06/27/mysql-database-backup-restore-using-java/#comment-18

 Reply

anto says:
May 6, 2014 at 16:39
thank u………..

Anonymous says:
May 21, 2014 at 14:33
how can restore database from client side to server without using file chooser in java

 Reply
banumathi says:
May 24, 2014 at 12:28
hi omindu,

pls help me for take db backup

public static boolean backupDB() {
String dbUserName = “root”;
String dbPassword = “sa”;
String dbName = “hms”;
String source = “\”C:/dataBackup/table.sql\””;

String[] executeCmd = new String[]{“C:\\Program Files\\MySQL\\MySQL Server 5.0\\bin\\mysql.exe”, “–
user=” + dbUserName, “–password=” + dbPassword, dbName, “-e”, “source ” + source};

background image

11/01/2019

MySQL Database Backup & Restore Using Java – Omindu's Blog

https://omindu.wordpress.com/2011/06/27/mysql-database-backup-restore-using-java/

29/35

Process runtimeProcess;

try {

runtimeProcess = Runtime.getRuntime().exec(executeCmd);

int processComplete = runtimeProcess.waitFor();

if (processComplete == 0) {

System.out.println(“Backup restored successfully”);

return true;

} else {

System.out.println(“Could not restore the backup”);

}
} catch (Exception e) {
e.printStackTrace();
}
return false;
}

it returns “Could not restore the backup”

 Reply
banumathi says:
May 24, 2014 at 13:59
hi omindu,

i followed ur code and instruction… but it’s not work fine…
if you can pls help me…

public static boolean backupDB() {
Process p = null;
try {
Runtime runtime = Runtime.getRuntime();
p = runtime.exec(“C:/Program Files/MySQL/MySQL Server 5.0/bin/mysqldump -h remotehostip -u root -psa
hms –tables feet_inches lab_test_take -r D:\\backup.sql”);
int processComplete = p.waitFor();
if (processComplete == 0) {
System.out.println(“Backup created successfully!”);
return true;
} else {
System.out.println(“Could not create the backup”);
}

} catch (Exception e) {
e.printStackTrace();
}
return false;
}

it returns “Could not create the backup”

background image

11/01/2019

MySQL Database Backup & Restore Using Java – Omindu's Blog

https://omindu.wordpress.com/2011/06/27/mysql-database-backup-restore-using-java/

30/35

it create empty backup.sql form… it does’t contain any backup…

 Reply

banumathi says:
May 24, 2014 at 15:49
hi,

I got db backup…
using –force -f
This is used for, Continue even if an SQL error occurs during a table dump…

thanks advance

 Reply

Tory says:
June 12, 2014 at 21:35
If some oone needs expert vikew concerning running a blog thsn i
advise him/her to goo to see thi blog, Keepp uup tthe
pleasan job.

 Reply
Anonymous says:
August 23, 2014 at 18:02
the restore code run two times and then stop and showing me the message Could not restore the backup how i
solve it ?

 Reply
Bhagaban says:
September 25, 2014 at 13:32
i have SQL Dump file ,i want to convert my SQL Dump to SQLite Dump using java code ..how we convert
please put a comment .

 Reply
sandya says:
October 6, 2014 at 15:12
Hi I want to backup pc1 database from pc2 Please provide the code

 Reply
sandya says:
October 6, 2014 at 15:13
Please provide the code

 Reply
sandya says:
October 6, 2014 at 15:22
I tried like this

public class Bean {

public static void getBackup(String user, String pwd, String dbName,
String tblName, String host, String port, String saveFilePath) {

saveFilePath=saveFilePath+”\\dumpFile.exe”;
System.out.println(saveFilePath+”\t”+user+”\t”+pwd+”\t”+dbName+”\t”+tblName+”\t”+host+”\t”+port);
//boolean res=getDumpFile(dumpPath,saveFilePath) ;–add-drop-database -B
String cmd=saveFilePath+” -h “+host+” -P “+port+” -u”+user+” -p”+pwd+” “+dbName+” “+tblName+” -

background image

11/01/2019

MySQL Database Backup & Restore Using Java – Omindu's Blog

https://omindu.wordpress.com/2011/06/27/mysql-database-backup-restore-using-java/

31/35

rD:/info.sql”;
try{
Process runtimeProcess=Runtime.getRuntime().exec(cmd);
InputStream is = runtimeProcess.getInputStream();

int byteRead = -1;
while ((byteRead = is.read()) != -1) {
System.out.print((char)byteRead );
}
int processComplete = runtimeProcess.waitFor();

if(processComplete == 0){
System.out.println(“Backup taken successfully”);
} else {
System.out.println(“Could not take mysql backup “+processComplete);
}
}catch(Exception e){
e.printStackTrace();
}
}

}

When I was taking backup for the same PC Its working fine. But When I was taking backup from pc2 for pc1
database I got “Could not take mysql backup”.

Please help me.

 Reply

Omindu says:
November 11, 2014 at 15:35
Hi,
Sorry for the delayed reply. I think you should enable remote access in the server in order to access the
database from a different PC.

 Reply

Xerox Shah says:
November 8, 2014 at 02:18
Hi, Thanks for the help.

I tried this restore command in windows, it worked fine but when I run on ubuntu 14.4, I can’t execute this.

[Windows Command works fine]:
String commandd = mysql + ” –user=” + username + ” –password=” + password + ” -D ” + database + ” -e\””
+ “source ” + restoreFile + “\””;

[Can’t run on Ubuntu the above command, I tried this command as well]:
String restoreFile = “/home/svd/test.sql”;
String[] cmd = new String[]{ mysql, “–user=” + database, “–password=” + password, database, ” -e”, “source ”
+ restoreFile };

Please help me out.

 Reply
Xerox Shah says:
November 11, 2014 at 15:24

background image

11/01/2019

MySQL Database Backup & Restore Using Java – Omindu's Blog

https://omindu.wordpress.com/2011/06/27/mysql-database-backup-restore-using-java/

32/35

Hay Thanks a lot! I had a problem with “space” in command, when I followed your this command:

String[] executeCmd = new String[]{“D:\\Copies\\10-10-2013\\server – Copy (2\\bin\\mysql.exe”, “–user=” +
dbUserName, “–password=” + dbPassword, dbName,”-e”, “source “+source};

I am able to execute it on Ubuntu. Thanks a lot!

 Reply
Edwin says:
November 24, 2014 at 21:07
I have tried this code and it is not working:

public class dbBackup {

public boolean backupDB(String dbName, String dbUserName, String dbPassword, String path) {

String executeCmd = “mysqldump -u ” + dbUserName + ” -p” + dbPassword + ” –add-drop-database -B ” +
dbName + ” -r ” + path;
Process runtimeProcess;
try {

runtimeProcess = Runtime.getRuntime().exec(executeCmd);
int processComplete = runtimeProcess.waitFor();

if (processComplete == 0) {
System.out.println(“Backup created successfully”);
return true;
} else {
System.out.println(“Could not create the backup”);
}
} catch (Exception ex) {
ex.printStackTrace();
}

return false;
}

public static void main(String[] args){
dbBackup bb = new dbBackup();
bb.backupDB(“apartments”,”root”, “”, “\”C:/VLC/dbBackup.sql\””);

}
}

Below is the error:

java.io.IOException: Cannot run program “mysqldump”: CreateProcess error=2, The system cannot find the
file specified
at java.lang.ProcessBuilder.start(ProcessBuilder.java:1041)
at java.lang.Runtime.exec(Runtime.java:617)
at java.lang.Runtime.exec(Runtime.java:450)
at java.lang.Runtime.exec(Runtime.java:347)
at dbBackup.main(dbBackup.java:40)
Caused by: java.io.IOException: CreateProcess error=2, The system cannot find the file specified
at java.lang.ProcessImpl.create(Native Method)
at java.lang.ProcessImpl.(ProcessImpl.java:385)

background image

11/01/2019

MySQL Database Backup & Restore Using Java – Omindu's Blog

https://omindu.wordpress.com/2011/06/27/mysql-database-backup-restore-using-java/

33/35

at java.lang.ProcessImpl.start(ProcessImpl.java:136)
at java.lang.ProcessBuilder.start(ProcessBuilder.java:1022)
… 4 more
BUILD SUCCESSFUL (total time: 2 seconds)

What might be the problem?

 Reply

Omindu says:
November 24, 2014 at 22:03
Hi Edwin,
One possible reason for this is, not having the MySQL bin folder in your path variables. You can check this
by simply opening a command prompt and entering mysqldump . If the command is not recognized, that
means MySQL bin folder is not in your path variables. Hope this helps.

 Reply

Edwin says:
November 26, 2014 at 00:04
True it it not there . How do i fix that.

Omindu says:
November 26, 2014 at 00:29
Follow this: http://www.javadomain.in/mysql-recognized-internal-external-command-operable-
program-batch-file/

ravikant verma says:
February 19, 2015 at 12:00
Hi..For restoring the database…how you are giving the source path of the file .In IE its taking the full qualified
name,whereas in chrome and firefox its taking only name.So,its not getting the full path.How you are dong
that.Thnx in advance

 Reply

Omindu says:
February 19, 2015 at 12:43
Hi ravikant,

Can you explain a bit more about your application ? Are you trying to pass the location of the backup file
through a web page ?

 Reply

ravikant verma says:
February 19, 2015 at 13:28
Thnxx for the instant reply..Yes i am passing the location from webpage.there is a browse button from where i
m geeting the path of the sql file.its working f9 in case of IE but full qualified path is not coming in chrome and
mozilla.Searched a lot on net,found tht due to security reason they have blocked this feature.Thnx

 Reply

Omindu says:
February 19, 2015 at 13:45
I personally haven’t tried out what you are trying to do. However I found this link. In the comments there
are some working solutions. Hope this will help. http://forums.asp.net/t/1333198.aspx?
How+to+get+the+full+file+path+from+asp+FileUpload+

 Reply

Honorato Dalaguit III says:

background image

11/01/2019

MySQL Database Backup & Restore Using Java – Omindu's Blog

https://omindu.wordpress.com/2011/06/27/mysql-database-backup-restore-using-java/

34/35

March 1, 2015 at 09:07
sir Omindu, please help me! I can’t restore backup. this is my code…
================================================================
================================================================
public boolean restoreDB(String dbUserName, String dbPassword, String source) {
String[] executeCmd = new String[]{“C:\\Program Files (x86)\\MySQL\\MySQL Server 5.1\\bin\\mysql.exe”,
“–user=” + dbUserName, “–password=” + dbPassword,”-e”, “source “+source};
Process runtimeProcess;
try {
runtimeProcess = Runtime.getRuntime().exec(executeCmd);
int processComplete = runtimeProcess.waitFor();
if (processComplete == 0) {
System.out.println(“Backup restored successfully”);
return true;
} else {
System.out.println(“Could not restore the backup”);
}
} catch (Exception ex) {
ex.printStackTrace();
}
return false;
}
=================================================================
private void jButtonRestoreActionPerformed(java.awt.event.ActionEvent evt) {
restoreDB(“root”, “1234”, jTextField2.getText().toString());
}
=================================================================

 Reply

Omindu says:
March 1, 2015 at 10:01
Do you get any exceptions while running the code ?

Also Check whether you can restore the database by only using the command line. If not, the command line
will prompt you the related error.

 Reply

Honorato Dalaguit III says:
March 1, 2015 at 11:09
Good day sir! Actually there’s no error or any exceptions while this code is running. But the problem is,
it will only say “Could not restore the backup” after I located the SQL File from a certain location.
Please help me sir. Sir, pardon me but I don’t know how execute restore from cmd. I already put the
MySQL bin path in Windows Environment Variables. Please HELP ME SIR!

Omindu says:
March 1, 2015 at 17:33
If you are using the method you mentioned above to restore the db, the database should already exist or
an ‘add database’ statement should be there in the backup file. If the db is not already created, create
one and re run the program.

You can follow the below link to see how the db can be restored using the command line.

http://webcheatsheet.com/sql/mysql_backup_restore.php

Nagendran says:

background image

11/01/2019

MySQL Database Backup & Restore Using Java – Omindu's Blog

https://omindu.wordpress.com/2011/06/27/mysql-database-backup-restore-using-java/

35/35

February 9, 2016 at 20:00
try {
String source = “\\”D:/backup.sql\\””;
String databaseName = “nag”;//database name
String userName = “root”;//username of mysql
String password = “root”;//password of myql
int processComplete;// this variable for verify the process
String[] executeCmd = new String[]{“mysql”, databaseName, “-u” + userName, “-p” + password, “-e”,
“source”+”\”D:/backup.sql/”}; //sava the command in a array
Process runtimeProcess = Runtime.getRuntime().exec(executeCmd);// execute the command

processComplete = runtimeProcess.waitFor();// get the result to variable

if (processComplete == 1) {// if return value equal to 1 then failed the process

JOptionPane.showMessageDialog(null, “Restore Failed”);
} else if (processComplete == 0) {
{// if return value equal to 0 then failed the process

JOptionPane.showMessageDialog(null, “Restore Completed”);

}
}

} catch (Exception ex) {

JOptionPane.showMessageDialog(null, ex);

}

i have the backup file in D: but it shows exception like java.io.IOException: Cannot run program
“mysqldump”: CreateProcess error=2, The system cannot find the file specified. please reply me. sorry for my
foolish english

 Reply

Omindu says:
February 10, 2016 at 12:50
Can you execute the ‘mysqldump’ command from command line? If not, most probably you have not added
the MySQL bin directory to your Windows system PATH environment variable.

 Reply

Blog at WordPress.com.


Wyszukiwarka

Podobne podstrony:
Building A Database Driven Website Using PHP And Mysql 2000 Yank
Yank Kevin Building a Database Driven Web Site Using PHP and MySQL
Creating a dd dcfldd Image Using Automated Image & Restore (AIR) HowtoForge Linux Howtos and Tutor
Next Gen VoIP Services and Applications Using SIP and Java
Delphi Creating a Database Application using Delphi
using uml for modeling a distributed java application 1997
2005 12 Reaching Base Building a Database Application Using Ooo Base
2001 11 Using the Staroffice Database
3 using c
Java Media FreamWork
3 Data Plotting Using Tables to Post Process Results
java 2
Printer Backup Server Printer S Nieznany
Projekt java
JAVA tablice

więcej podobnych podstron