MySQL export with Java doesn't work - java

This is the code I created for exporting the database. The problem is, the file is not exported, and the code shows no error message.
public boolean exportDatabase(String fromServer,
String FileName,
String FilePath,
int ExportOpions) {
try {
String dbName ="NMSAzzist";
String dbUser = "root";
String dbPass ="root";
String dumbPath = "C:\\Program Files\\MySQL\\MySQL Server 5.1\\bin\\";
String executeCmd = dumbPath+"mysqldump -u "+dbUser+ "-p"+dbPass+" "+dbName+ "-r "+FilePath+ "";
Process runtimeProcess = Runtime.getRuntime().exec(executeCmd);
int processComplete = runtimeProcess.waitFor();
if (processComplete == 1) { // if values equal 1 process failed
JOptionPane.showMessageDialog(null, "Backup Failed");//display message
} else if (processComplete == 0) {
JOptionPane.showMessageDialog(null, "\n Backup created Successfully..");
// display message
}
return true;
} catch (final Exception ex) {
NmsLogger.writeErrorLog("Database Connection Failed ", ex.toString());
NmsLogger.writeDebugLog(ex);
return false;
}
How can I export the database to a path specified in the variable FilePath in the name FileName? How can I solve the issue?
And BTW, can i use the following to import the same??
String[] executeCmd = new String[]{"mysql", databaseName, "-u" + userName, "-p" + password, "-e" + FileName };

You first try your executeCmd can run successfullly in db.
In your executeCmd is syntax error. Your code left file name in execution command in
String executeCmd = "/" + dumbPath + "mysqldump -u " + dbUser
+ " -p" + dbPass + " " + dbName + " -r " + FilePath + "\\"
+ FileName;
Check the manual
This works for me.
public class exportDataBase {
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
exportDatabase("", "Sma_test.sql", "C:", 0);
}
public static boolean exportDatabase(String fromServer, String FileName,
String FilePath, int ExportOpions) {
try {
String dbName = "dmsdev";
String dbUser = "root";
String dbPass = "root";
String dumbPath = "C:\\Program Files\\MySQL\\MySQL Server 5.1\\bin\\";
String executeCmd = "/" + dumbPath + "mysqldump -u " + dbUser
+ " -p" + dbPass + " " + dbName + " -r " + FilePath + "\\"
+ FileName;
System.out.println(executeCmd);
Process runtimeProcess = Runtime.getRuntime().exec(executeCmd);
int processComplete = runtimeProcess.waitFor();
System.out.println("processComplete: " + processComplete);
if (processComplete == 1) {// if values equal 1 process failed
System.out.println("Backup failed");
}
else if (processComplete == 0) {
System.out.println("Backup Success");
}
return true;
} catch (final Exception ex) {
System.out.println("Connection failed");
return false;
}
}
}

Didn't you forget the Filename?
String executeCmd =dumbPath+"mysqldump -u "+dbUser+ "-p"+dbPass+" "+dbName+ "-r "+FilePath+"\\"+Filename"";

Make it as :
// you did not give file name.
String executeCmd = "cmd " + dumbPath+"mysqldump -u "+dbUser+ "-p"+dbPass+" "+dbName+ "-r "+FilePath+ "\\" + filename;
// I tried running I am getting error code 13.
I think you should make :
if(processComplete != 0) {
//error with error code
} else {
//success
}
instead of
if (processComplete == 1) {// if values equal 1 process failed
System.out.println("Backup failed");
}
else if (processComplete == 0) {
System.out.println("Backup Success");
}
because error-code returned may be other than 0 and 1.
Suggestion : Use Apache Commons exec API, this is more sophisticated than Runtime.exec.

Related

How to create Backup of a mysql database in java

I have seen there are many articles on this issue and I tried all of them but I am still fail to create a backup using java.
Here is my code:
public class CreateBackup {
public static void main(String[] args) {
try {
File file = new File("mysqlBackup");
if (!file.isDirectory()) {
file.mkdir();
}
String fileName = "backup_" + new Date().getTime() + ".sql";
String path = file.getAbsolutePath() + "/" + fileName;
String cmd = "/usr/bin/mysqldump -uroot -proot userDb > " + path; //-The root after u is the mysql database user name, and the 123456 followed by - p is the user password. Note that there is no space; dbName fills in the database name that needs to be backed up, and the greater than sign is followed by the generated file path
System.out.println("path " +cmd);
Process runtimeProcess = Runtime.getRuntime().exec(cmd );
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 (Exception ex) {
ex.printStackTrace();
}
}
}
I tried to run in ubuntu also tried with windows but mentioning mysqldump full path "C:\Program Files\MySQL\MySQL Server 5.7\bin\mysqldump". Why my code is always returning backup failure? Help me, please. Thanks in advance.
I fixed this code by adding more lines. while executing.
File f = new File(file, new Timestamp(System.currentTimeMillis()).getTime() + ".sql");
String path = f.getPath();
String username = "root";
String password = "root";
String dbname = "userDb";
String executeCmd = "/usr/bin/mysqldump -u" + username + " -p" + password
+ " --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);
System.out.println(executeCmd);
// runtimeProcess = Runtime.getRuntime().exec(executeCmd);
int processComplete = runtimeProcess.waitFor();
System.out.println("processComplete" + processComplete);
if (processComplete == 0) {
System.out.println("Backup created successfully");
} else {
System.out.println("Could not create the backup");
}
} catch (Exception ex) {
ex.printStackTrace();
}
Hope it will help others..

Dispatch File from AS400 to Mainframe using FTPS

Currently, My system send file from AS400 to Mainframe by FTP. The downstream Mainframe system will not support FTP any more. FTPS will be the only way to send files to it.
Currently we use com.ibm.as400.access.FTP and this package to execute FTP command. I want to know What package can be used by FTPS from AS400 to Mainframe.
currently ftp code is as follows:
boolean FTPFile(String filepath, String filename, String country) {
String ftpresult = "";
String region = bundle.getString("region." + country);
FTP ftp = new FTP(ftpHost, ftpId, ftpPw);
try {
if (country.equals("766") || country.equals("858")
|| country.equals("761") || country.equals("836")) {
ftp.setDataTransferType(FTP.BINARY);
}
if (ftp.connect()) {
getLogMsg().append("FTPing SIF file. Region = " + region,
LogMsg.TEXT_MSG);
String sendname = "'" + ftpDataset + country + ".LSIFATB'";
getLogMsg().append(
"sending file: = " + filepath + filename + " as "
+ sendname, LogMsg.TEXT_MSG);
// Korea
if (country.equals("766") || country.equals("761")) {
ftp.issueCommand("ltype c 933");
// ftpresult = ftp.issueCommand("type b 6");
}
// Taiwan
if (country.equals("858") || country.equals("836")) {
ftp.issueCommand("ltype c 937");
// ftpresult = ftp.issueCommand("type b 8");
}
boolean ftp_res = ftp.put(filepath + filename, sendname);
// System.out.println("ftp result: " + ftp_res);
getLogMsg().append("ftp result (sending SIF): " + ftp_res,
LogMsg.TEXT_MSG);
ftpresult = ftp.issueCommand("site filetype=jes");
System.out.println("ftp command result = " + ftpresult);
String jobname = bundle.getString("app.sif.jobname." + country);
// String jobname = "CISBL30D";
ftp.setDataTransferType(FTP.ASCII);
ftp_res = ftp.put(bundle.getString("app.sif.directory") + "/"
+ region + country + "/jcl.txt", "jcl.txt '" + jobname
+ "'");
getLogMsg().append("ftp result (sending jcl): " + ftp_res,
LogMsg.TEXT_MSG);
return true;
}
} catch(...) {}
}
I've used the Apache COMMONS Net module to do normal FTP.
It does have a FTPSClient class that should do what you want.

Back-up in JAVA takes too much time to execute

So, I want to create a backup file for my mysql database.
However when i tried to run the code it takes too much time and still no response.
This is my code:
public void backup() {
String fileName = "";
URL url;
JFileChooser backupFile = new JFileChooser();
backupFile.setCurrentDirectory(new java.io.File("."));
backupFile.setDialogTitle("Select the Path of Backup");
backupFile.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
backupFile.setAcceptAllFileFilterUsed(false);
backupFile.setApproveButtonText("Backup Database");
backupFile.setSize(700, 400);
backupFile.setLocation(100, 100);
if (backupFile.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
try {
url = backupFile.getSelectedFile().toURL();
fileName = url.toString().replaceAll("file:/", "").trim();
System.out.println(fileName);
} catch (MalformedURLException e) {
e.printStackTrace();
}
} else {
System.out.println("No Selection");
}
try {
String dbName = AppVars.dbName;
String dbUser = AppVars.dbUserName;
String dbPass = AppVars.dbPassword;
if (!fileName.equals("") && fileName != null) {
String savePath = fileName + "ssmis.sql";
String executeCmd = AppVars.xamppUrl + "mysqldump -u " + dbUser + " -p " + dbPass + " --database " + dbName + " -r " + savePath;
System.out.println(executeCmd);
Process runtimeProcess = Runtime.getRuntime().exec(executeCmd);
int processComplete = runtimeProcess.waitFor();
System.out.println("Here");
if (processComplete == 0) {
JOptionPane.showMessageDialog(null, "Backup Successful", "Success", JOptionPane.INFORMATION_MESSAGE);
} else {
JOptionPane.showMessageDialog(null, "Backup Failed", "Failed", JOptionPane.INFORMATION_MESSAGE);
}
}
} catch (Exception ex) {
JOptionPane.showMessageDialog(null, "Error at Backup " + ex);
}
}
What am i doing wrong?
I am not sure if it is possible to take backup of all the tables individually in mysql, but if it is possible create a multi-threaded application which will take backup from all the tables and they will create backup file individually for each table which probably you can merge from your code. Use count down latch in each thread. Once the processing of threads are done you can merge the files.
If you're running this code in an event listener it will freeze the GUI until the backup completes. You need to run it in a separate thread.

MYSQL Backup using java GUI

I am trying to backup my database and this is the code I've written but for some reason it is not backing up?? i am using local host (MAMP) and the operating system I am using is MAC OSX.
public boolean databaseBackup(String dbName, String dbUserName, String dbPassword, String path) {
String qu = "/Applications/MAMP/Library/bin/mysqldump -u" + dbUserName + " -p" + dbPassword + " --database" + dbName + " -r " + path;
System.out.println(qu);
Process runtimeProcess;
Properties pr = new Properties();
pr.setProperty("user", "username");
pr.setProperty("password", "password");
Connection con = null;
PreparedStatement stmt = null;
try {
con = DriverManager.getConnection("jdbc:mysql://localhost:8889/Database", pr);
runtimeProcess = Runtime.getRuntime().exec(qu);
int processComplete = runtimeProcess.waitFor();
if (processComplete == 0) {
System.out.println("5");
System.out.println("Backed up");
return true;
} else {
System.out.println("Not Backed up");
}
} catch (Exception ex) {
ex.printStackTrace();
}
return false;
}
}
in my jframe form I wrote this:
code.databaseBackup("Database","root", "root", "/Users/dipeshramesh/Dropbox/TeamProject/TeamProject2.sql");
so when a person press backup button it calls code.databaseBackup method and dose its jobs.
if I run this it shows a message "Not Backed up" dose any know this?
use String qu = "/Applications/MAMP/Library/bin/mysqldump -u" + dbUserName + " -p" + dbPassword + " --database" + dbName + " > " + path;
command - /Applications/MAMP/Library/bin/mysqldump -u yourUser -p --opt yourdb > yourdump.sql

Java FTP file get issue

I have a application that runs as a schedule.It connect to ftp server and get files from remote folder.scheduler runs in every 5min time.Sometimes when there are lot of files in remote location, scheduler runs again while first cycle is running.In such situation some times it download 0 size files even actual file size is greater than 0 in remote location.Does anyone have any idea why this happen?
below is the code to import files.
private void importEDIFiles(String host, String user, String password, String path, String road) {
try {
String edi824Path = path + "/" + EDI_824_FOLDER;
FTPBroker ftpBroker = new FTPBroker(host, user, password, edi824Path);
FTPClient client = ftpBroker.makeFTPConeection();
String os = client.getSystemName();
client.setFileTransferMode(FTP.ASCII_FILE_TYPE);
File edi824File = null;
File edi824Filebak = null;
ArrayList<FTPFile> files;
try {
FTPFile[] ftpfiles = client.listFiles();
logger.info("\t" + ftpfiles.length + " files are in ftp location ");
if (ftpfiles.length > 0) {
files = removeZeroFiles(ftpfiles);
for(int x=0;x<files.size();x++){
logger.info("name ---"+files.get(x).getName());
logger.info("size ----"+files.get(x).getSize());
}
String ftpFile = null;
logger.info("\t" + files.size() + " downloading from " + road + " rail road.");
for (int i = 0; i < files.size(); i++) {
ftpFile = files.get(i).getName();
logger.info("\t" + ftpFile + " is downloading....");
// logger.info("\t" + ftpFile + " size ...." + ftpFile.isEmpty());
String source = destinationFilePath + pathSeparator + road + pathSeparator + ftpFile;
String target = edi_824backupFilePath + pathSeparator + road + pathSeparator + ftpFile;
edi824File = new File(source);
edi824Filebak = new File(target);
FileOutputStream fosout = new FileOutputStream(source);
boolean isRetrieved = client.retrieveFile(ftpFile, fosout);
logger.debug("isRetrieved : " + isRetrieved);
FileUtils.copyFile(edi824File,edi824Filebak);
fosout.flush();
fosout.close();
boolean isDelete = client.deleteFile(ftpFile);
logger.debug("isDelete : " + isDelete);
}
} else {
logger.info("No files to Pull in the FTP Location for " + user);
//throw new RuntimeException("No files to Pull in FTP Location.");
}
} catch (Exception e) {
logger.error(e,e);
e.printStackTrace();
} finally {
client.logout();
client.disconnect();
}
} catch (Exception ex) {
logger.error(ex, ex);
ex.printStackTrace();
}
}
you can use a flag boolean isRunning(), setRunning(boolean ), and synchronize your code so that two or more threads would not run the same method at the same time

Categories

Resources