Error in executing mysql command from java - java

I was trying to execute the mysql command using java but this always keeps giving error.
String dbName = "dth";
String dbUser = "root";
String dbPass = "root";
String executeCmd = "";
executeCmd = "mysqldump -u " + dbUser + " -p" + dbPass + " " + dbName + " -r C:\\backup.sql";
Process runtimeProcess = Runtime.getRuntime().exec(executeCmd);
int processComplete = runtimeProcess.waitFor();
if (processComplete == 0) {
System.out.println("Backup taken successfully");
} else {
System.out.println("Could not take mysql backup");
}
} catch (Exception e) {
System.out.println(e.getMessage());
}
I tried the above code but I couldn't get it done, keeps giving me
CreateProcess error=2, The system cannot find the file specified
error.
I have tried it by creating a .sql file on the location and still I get the same error.

Add the directory in which mysqldump resides into your path environment variable or use the full pathname I.e c:\directory\mysqldump

Related

Restoring MySQL .sql dump not working when trying to local XAMPP MySQL server

Below is the code I am trying to use restore a .sql dump to a MySQL database on a local XAMPP server. I just can't see what I am doing wrong. Can anyone help?
try {
String dbName = "Database";
String dbUser = "root";
String dbPass = "";
String[] executeCmd = new String[]{"/Applications/XAMPP/bin/mysql", " --user=" + dbUser, " --password=" + dbPass, " "+dbName, " -e", " source "+s};
Process runtimeProcess = Runtime.getRuntime().exec(executeCmd);
int processComplete = runtimeProcess.waitFor();
System.out.println(processComplete);
if (processComplete == 0) {
JOptionPane.showMessageDialog(null, "Successfully restored);
} else {
JOptionPane.showMessageDialog(null, "Error restoring");
}
} catch (IOException | InterruptedException | HeadlessException ex) {
JOptionPane.showMessageDialog(null, "Error" + ex.getMessage());
}
Why don't u upload your mysql dump through phpmyadmin.....
Steps:
1) Go to Phpmyadmin
2) Go to Import
3) Select the dump
4) Upload it it database...
As u have already mentioned that u r using Xampp server, u can easuly upload dump through phpmyadmin

mysqldump file creates an empty sql file

i apply comment 1 and 2 alternatively.But i didn't get myqldump file using java.mysqldump working in cmd. i think in cmd it ask password after typing mysqldump comment. please help me fast.thanks in advance.
String dumpCommand = "C:\\Program Files\\MySQL\\MySQL Server 5.0\\bin\\mysqldump" + " -u " + user + " -p" + " " + database + " > " + path;
**//command 1**
Runtime rt = Runtime.getRuntime();
File test = new File(path);
PrintStream ps;
try {
// Process child = rt.exec("Cmd /c \"C:/Program Files/MySQL/MySQL Server 5.0/bin/mysqldump\" -u root -p saxco > "+path);//command 2
Process child = rt.exec(dumpCommand);
ps = new PrintStream(test);
InputStream in = child.getInputStream();
int ch;
while ((ch = in.read()) != -1) {
ps.write(ch);
System.out.write(ch);
}
As documented here you can specify the password in the command like this [...] -pPASSWORD [...]. Note that there must not be a space between the -p option flag and the actual password.
Keep in mind that specifying the password this way is a security risk!
If you don't use a password just don't use the -p option too.
String dumpCommand = "C:\Program Files\MySQL\MySQL Server 5.0\bin\mysqldump" + " -u " + user + database + " > " + path;
or this if you have one (without the gaps)
String dumpCommand = "C:\Program Files\MySQL\MySQL Server 5.0\bin\mysqldump" + " -u " + user + " -p" + password + " " + database + " > " + path;
try this-
String cmd="mysqldump -u "+USER+" -p"+PASSWORD+" "+database+" --routines -r"+PATH;
Runtime runtime = Runtime.getRuntime();
Process exec;
exec = runtime.exec(cmd);
int processComplete = exec.waitFor();
if(processComplete == 0){
System.out.println("Backup taken successfully in "+PATH+" on "+new Date());
} else {
System.out.println("Could not take mysql backup :ERROR:");
}

Simple Backup and Restore for mysql Database from Java

How to backup a mysql database from a java code such that:
It's saving path is dynamically allocated.
Spaces in Path do not create problems.
Path is generated using the executing jar file.
DBname,DBusername or DBpass are dynamically allotted.
Creating a specialized folder to save the backup file.
Note: The codes given below are one way of solving the problem and probably not the best method. Everything is changeable inside the code. If you do not have mysql in environment variables, add the path before mysqldump and mysql (e.g. For XAMPP, C:\xampp\mysql\bin\mysqldump)
(Hope, this will solve your problems. Took me a day to completely figure out everything and implement them properly)
Method for Backup:
public static void Backupdbtosql() {
try {
/*NOTE: Getting path to the Jar file being executed*/
/*NOTE: YourImplementingClass-> replace with the class executing the code*/
CodeSource codeSource = YourImplementingClass.class.getProtectionDomain().getCodeSource();
File jarFile = new File(codeSource.getLocation().toURI().getPath());
String jarDir = jarFile.getParentFile().getPath();
/*NOTE: Creating Database Constraints*/
String dbName = "YourDBName";
String dbUser = "YourUserName";
String dbPass = "YourUserPassword";
/*NOTE: Creating Path Constraints for folder saving*/
/*NOTE: Here the backup folder is created for saving inside it*/
String folderPath = jarDir + "\\backup";
/*NOTE: Creating Folder if it does not exist*/
File f1 = new File(folderPath);
f1.mkdir();
/*NOTE: Creating Path Constraints for backup saving*/
/*NOTE: Here the backup is saved in a folder called backup with the name backup.sql*/
String savePath = "\"" + jarDir + "\\backup\\" + "backup.sql\"";
/*NOTE: Used to create a cmd command*/
String executeCmd = "mysqldump -u" + dbUser + " -p" + dbPass + " --database " + dbName + " -r " + savePath;
/*NOTE: Executing the command here*/
Process runtimeProcess = Runtime.getRuntime().exec(executeCmd);
int processComplete = runtimeProcess.waitFor();
/*NOTE: processComplete=0 if correctly executed, will contain other values if not*/
if (processComplete == 0) {
System.out.println("Backup Complete");
} else {
System.out.println("Backup Failure");
}
} catch (URISyntaxException | IOException | InterruptedException ex) {
JOptionPane.showMessageDialog(null, "Error at Backuprestore" + ex.getMessage());
}
}
Method for Restore:
public static void Restoredbfromsql(String s) {
try {
/*NOTE: String s is the mysql file name including the .sql in its name*/
/*NOTE: Getting path to the Jar file being executed*/
/*NOTE: YourImplementingClass-> replace with the class executing the code*/
CodeSource codeSource = YourImplementingClass.class.getProtectionDomain().getCodeSource();
File jarFile = new File(codeSource.getLocation().toURI().getPath());
String jarDir = jarFile.getParentFile().getPath();
/*NOTE: Creating Database Constraints*/
String dbName = "YourDBName";
String dbUser = "YourUserName";
String dbPass = "YourUserPassword";
/*NOTE: Creating Path Constraints for restoring*/
String restorePath = jarDir + "\\backup" + "\\" + s;
/*NOTE: Used to create a cmd command*/
/*NOTE: Do not create a single large string, this will cause buffer locking, use string array*/
String[] executeCmd = new String[]{"mysql", dbName, "-u" + dbUser, "-p" + dbPass, "-e", " source " + restorePath};
/*NOTE: processComplete=0 if correctly executed, will contain other values if not*/
Process runtimeProcess = Runtime.getRuntime().exec(executeCmd);
int processComplete = runtimeProcess.waitFor();
/*NOTE: processComplete=0 if correctly executed, will contain other values if not*/
if (processComplete == 0) {
JOptionPane.showMessageDialog(null, "Successfully restored from SQL : " + s);
} else {
JOptionPane.showMessageDialog(null, "Error at restoring");
}
} catch (URISyntaxException | IOException | InterruptedException | HeadlessException ex) {
JOptionPane.showMessageDialog(null, "Error at Restoredbfromsql" + ex.getMessage());
}
}
If Hibernate is configured properly, this is cake:
Session session = HibernateUtil.getSessionFactory().openSession();
// for every table, have the bean implement Serializable and use the next 4 lines
List <TblBean> tblCollection = session.createCriteria(TblBean.class).list();
FileOutputStream backup = new FileOutputStream("backupOf"+TblBean.getClass().getName()+".dat");
ObjectOutputStream backupWriter = new ObjectOutputStream(backup);
backupWriter.write(tblCollection);
public static String getData(String host, String port, String user, String password, String db,String table) throws Exception {
//an "C:/xampp/mysql/bin/mysqldump" ---- location ito han mysqldump
Process run = Runtime.getRuntime().exec(
"C:/xampp/mysql/bin/mysqldump --host=" + host + " --port=" + port +
" --user=" + user + " --password=" + password +
" --compact --databases --add-drop-table --complete-insert --extended-insert " +
"--skip-comments --skip-triggers "+ db+" --tables "+table);
InputStream in = run.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(in));
StringBuffer temp = new StringBuffer();
int count;
char[] cbuf = new char[BUFFER];
while ((count = br.read(cbuf, 0, BUFFER)) != -1)
temp.append(cbuf, 0, count);
br.close();
in.close();
return temp.toString();
}
In addition to chettyharish's answer, if your server os is ubuntu the path should have front slash '/' instead of backslash '\' such as /path/to/your/file
For example: String savePath = "\"" + jarDir + "\\backup\\" + "backup.sql\"";
Will be : String savePath="/"+jarDir+"/backup/backup.sql"

backup mysql database java code

I tried to run the following code which is to create a backup of my database but it shows some run time errors.
But, I tried to run the System.out.println() output part, (which I've commented in the given code) in mysql shell and it worked.
It shows io file problem. Plz somebody help me.
package files;
public class tableBackup_1 {
public boolean tbBackup(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
{
System.out.println(executeCmd);//this out put works in mysql shell
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){
tableBackup_1 bb = new tableBackup_1();
bb.tbBackup("test","harin","1234","C:/Users/Master/Downloads/123.sql");
}
}
mysqldump -u harin -p1234 --add-drop-database -B test -r C:/Users/Master/Downloads/123.sql
java.io.IOException: Cannot run program "mysqldump": CreateProcess error=2, The system cannot find the file specified
at java.lang.ProcessBuilder.start(ProcessBuilder.java:460)
at java.lang.Runtime.exec(Runtime.java:593)
at java.lang.Runtime.exec(Runtime.java:431)
at java.lang.Runtime.exec(Runtime.java:328)
at files.tableBackup_1.tbBackup(tableBackup_1.java:12)
at files.tableBackup_1.main(tableBackup_1.java:34)
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.<init>(ProcessImpl.java:81)
at java.lang.ProcessImpl.start(ProcessImpl.java:30)
at java.lang.ProcessBuilder.start(ProcessBuilder.java:453)
... 5 more
Please check whether your Global PATH environment variable has <Path to MySQL>\bin in it (Do a echo %PATH% and see). Effectively you should be able to type your System.out.println() content in a Plain DOS prompt and should be able to run it.
Even with that if it doesn't work try changing the code to execute like below
runtimeProcess = Runtime.getRuntime().exec(new String[] { "cmd.exe", "/c", executeCmd });
This should ideally fix the issue.
UPDATE:
If you don't have it in the PATH environment variable change the code to following
String executeCmd = "<Path to MySQL>/bin/mysqldump -u " + dbUserName + " -p" + dbPassword + " --add-drop-database -B " + dbName + " -r " + path;
runtimeProcess = Runtime.getRuntime().exec(new String[] { "cmd.exe", "/c", executeCmd });
i tried this one but it didn't work so i replaced it with
this runtimeProcess = Runtime.getRuntime().exec(executeCmd);
and it worked
I solved this problem by giving full path to mysqldump.exe
You can get SO environment variables by
Map<String, String> env = System.getenv();
final String LOCATION = env.get("MYSQLDUMP");
I setup the system variable like this :
Variable Name : MYSQLDUMP
Value : D:\xampp\mysql\bin\mysqldump.exe
Now just execute this code below,
String executeCmd = LOCATION+" -u " + DBUSER + " --add-drop-database -B " + DBNAME + " -r " + PATH + ""+FILENAME
Process runtimeProcess = = Runtime.getRuntime().exec(executeCmd);
Note : If you don't have configured password for mysql server just remove the -p PASSWORD attribute from the code. And don't forget to restart your computer after creating a new system variable.

Exporting database through my java code

I want to export my MySQL database using my java code. But I have not found any way to do. What I want to do that there is a button in my app as "Export Database". When that button is clicked, my database should be exported to specified path. I have used the following code but it does'nt worked :
Runtime runtime = Runtime.getRuntime();
runtime.exec("C:\\Program Files\\MySql\\MySql Server 5.5\\bin\\mysqldump -u root -p myDatabase> D:\\backup.sql");
How should I do this task. Thanks.
Two problems :
the space between -p and the password
the space inside the path to the executable
Prefer this :
runtime.exec(new String[]{"C:\\Program Files\\MySql\\MySql Server 5.5\\bin\\mysqldump", "-u", "root", "-pmyDatabase" "> D:\\backup.sql"});
Note that if you have a problem with runtime.exec, you should look at the streams you can get from the returned Process. Not looking at those streams in case of error is a little like not looking at the exception when one is thrown.
Backup:
/******************************************************/
//Database Properties
/******************************************************/
String dbName = “dbName”;
String dbUser = “dbUser”;
String dbPass = “dbPass”;
/***********************************************************/
// Execute Shell Command
/***********************************************************/
String executeCmd = “”;
executeCmd = “mysqldump -u “+dbUser+” -p”+dbPass+” “+dbName+” -r backup.sql”;
}
Process runtimeProcess =Runtime.getRuntime().exec(executeCmd);
int processComplete = runtimeProcess.waitFor();
if(processComplete == 0){
out.println(“Backup taken successfully”);
} else {
out.println(“Could not take mysql backup”);
}
Restore:
/******************************************************/
//Database Properties
/******************************************************/
String dbName = “dbName”;
String dbUser = “dbUser”;
String dbPass = “dbPass”;
/***********************************************************/
// Execute Shell Command
/***********************************************************/
String executeCmd = “”;
executeCmd = new String[]{“/bin/sh”, “-c”, “mysql -u” + dbUser+ ” -p”+dbPass+” ” + dbName+ ” < backup.sql” };
}
Process runtimeProcess =Runtime.getRuntime().exec(executeCmd);
int processComplete = runtimeProcess.waitFor();
if(processComplete == 0){
out.println(“success”);
} else {
out.println(“restore failure”);
}
You can try this.
public void actionPerformed(ActionEvent evt)
{
private String m_MySqlPath="";
ResultSet res=null;
res = DBHandler.getInstance().executeQuery("select ##basedir",null);
while(res.next())
{
m_MySqlPath=res.getString(1) ;
}
m_MySqlPath = m_MySqlPath.replace("\\Data\\", "\\bin\\");
if (exportDB.isSelected()
{
try {
String executeCmd = m_MySqlPath + "\\mysqldump -u " + DB_USER
+" -p" + DB_PASSWORD + " " + DB_NAME + " -r " + "\""+FilePath + "\\"
+ FileName+"\"";
Process runtimeProcess = Runtime.getRuntime().exec(executeCmd, null);
BufferedReader r=new BufferedReader(new InputStreamReader(runtimeProcess.getInputStream()));
String s;
while((s=r.readLine())!=null)
{
System.out.println(s);
}
return true;
}
catch (final Exception ex) {
ex.printstackTrace();
return false;
}
}

Categories

Resources