use java to dump mysql database - java

I am using Ubuntu. I want to use java application to dump the MySQL database. Below are my code:
String userName = "root";
String userPassword = "root";
String oldDatabaseName = "testing";
String executeCommand = "";
executeCommand = "mysqldump -u "+userName+" -p"+userPassword+" --no-data "
+OldDatabaseName+" > testingbackup.sql";
Process runtimeProcess = Runtime.getRuntime().exec(executeCmd);
int processComplete = runtimeProcess.waitFor();
if(processComplete == 0){
System.out.println("Backup successful.");
}else{
System.out.println("Backup failed.");
}
But, when I run the above program, I always get the "Backup failed" message.
Am I writing the wrong code? And what library/file I need to include in my java application? Any help please.

This is working fine in my windows machine.
package org.some.test;
import java.io.File;
public class dateformat {
private static final String dbUserName = "root";
private static final String dbPassword = "manager";
private static final String dbName = "opencms";
public static void main(String[] args){
try {
File path =new File("D:\\dump1.sql");
String[] executeCmd = new String[]{"C:/Program Files/MySQL/MySQL Server 5.6/bin/mysql", "--user=" + dbUserName, "--password=" + dbPassword,""+ dbName,"-e", "source "+path};
Process p = Runtime.getRuntime().exec(executeCmd);
int processComplete = p.waitFor();
if (processComplete == 0)
{
System.out.println("Restore created successfully");
//return true;
}
else
{
System.out.println("Could not restore");
}
} catch (Exception e) {
e.printStackTrace();
}
}
}

It seems to me you omitted a space between -p and quote:
-p "+userPassword+
^-- insert space here

Related

MySQL dump from java with where condition on multiple table (Or) Multiple command line

String executeCmd1 = "";
String executeCmd2 = "";
executeCmd1 = "C:/wamp64/bin/mysql/mysql5.7.14/bin/mysqldump -u "+dbUser+" -p"+dbPass+" "+dbName+" "+dbTable+" --where=id="+whereStatement+" --single-transaction --skip-lock-tables --no-create-info -r D:/backup.sql";
executeCmd2 = "C:/wamp64/bin/mysql/mysql5.7.14/bin/mysqldump -u "+dbUser+" -p"+dbPass+" "+dbName+" "+dbTable_1+" --where=course_id="+whereStatement+" --single-transaction --skip-lock-tables --no-create-info >> D:/backup.sql";
System.out.println(executeCmd1);
System.out.println(executeCmd2);
Process runtimeProcess =Runtime.getRuntime().exec(executeCmd1);
int processComplete = runtimeProcess.waitFor();
if(processComplete == 0){
System.out.println("Backup taken successfully");
Process runtimeProcess1 =Runtime.getRuntime().exec(executeCmd2);
int processComplete1 = runtimeProcess.waitFor();
} else {
System.out.println("Could not take mysql backup");
}
while running the application first command line executes and backup is saved in file. Then running the second command but it's not working.
You could do this sort of thing with ProcessBuilder:
public class Dump {
public static void main(String[] args) {
try {
// (NB: All variables previously declared)
String[] executeCmd2 = {
"cmd.exe",
"/c",
"C:/wamp64/bin/mysql/mysql5.7.14/bin/mysqldump",
"-u",
dbUser,
"-p",
dbPass,
dbName,
dbTable_1,
"--where=course_id=",
whereStatement,
"--single-transaction",
"--skip-lock-tables",
"--no-create-info",
">> D:/backup.sql"
};
ProcessBuilder pb = new ProcessBuilder(executeCmd2);
pb.inheritIO();
pb.start();
} catch (Throwable t) {
t.printStackTrace();
}
}
}

Not able to open Edge Browser by Runtime.exec method

We are facing an issue where the below code is not able to open Microsoft Edge by running the command.
import java.io.IOException;
import java.io.InputStream;
public class ProcessTest {
private static final String NO_FRAME_MERGING_CMD_EDGE = "cmd.exe /c start microsoft-edge:";
private static final Object DOUBLE_QUOTE = "\"";
public static void main(String[] args) throws IOException {
Runtime rt = Runtime.getRuntime();
String url = "http://google.com";
url = new StringBuilder().append(DOUBLE_QUOTE).append(url).append(DOUBLE_QUOTE).toString();
System.out.println(NO_FRAME_MERGING_CMD_EDGE+ url);
Process process = rt.exec(NO_FRAME_MERGING_CMD_EDGE+ url);
printErrorlog(process);
}
public static void printErrorlog(Process process) {
try {
if (process != null && isProcessTerminated(process)) {
StringBuffer string_error = new StringBuffer();
InputStream errorStream = process.getErrorStream();
if (errorStream != null) {
int c = 0;
while ((c = errorStream.read()) != -1) {
string_error.append((char) c);
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
private static boolean isProcessTerminated (Process process) {
try {
process.exitValue();
} catch (IllegalThreadStateException itse) {
itse.printStackTrace();
return false;
}
return true;
}
}
In the logs we see
cmd.exe /c start microsoft-edge:"http://google.com"
java.lang.IllegalThreadStateException: process has not exited
at java.lang.ProcessImpl.exitValue(Native Method)
at ProcessTest1.isProcessTerminated(ProcessTest1.java:40)
at ProcessTest1.printErrorlog(ProcessTest1.java:22)
at ProcessTest1.main(ProcessTest1.java:16)
But the browser does not open.
When we run the command below in a bash file or on the command line, the windows is able to opening Edge. So I am not able to understand why it is not opening by Java.
cmd.exe /c start microsoft-edge:"http://google.com"
We are using jdk 6 to run the programm.

How to create a new User remotely using Poweshell from inside a java program?I am getting following error

I want to run a PowerShell command for create user using Java on a remote windows machine, I am writing this code in eclipse.
And below is the output, tried every reference and forms to resolve this issue can someone help me with this.
The command works on PowerShell command line, but it is not working in Java.
public class PowerShellSession {
private static String subModule = "PowerShellSession";
String targetIpAddress;
String username;
String password;
public static Object connectPShellLock = new Object();
public PowerShellSession() {}
public void exec(String cmd, String credentials) {
//String ex = "New-LocalUser -Name \"User02\" -Description \"Description of this account.\" -NoPassword";
String ex = credentials +" Invoke-Command -ScriptBlock {" + cmd + "} -ComputerName " + targetIpAddress +" -Credential $mycred";
String[] args = new String[] { "powershell", ex};
try {
execRemote(args);
} catch (IOException e) {
e.printStackTrace();
}
}
public void close() {
String command = "Exit-PSSession";
String[] args = new String[] { "powershell", command};
try {
execRemote(args);
} catch (IOException e) {
e.printStackTrace();
}
}
private String getCredentials(String domain, String userName,
String password) throws IOException {
String creds = "$Username = '"+userName+"';$PlainPassword ='" + password
+ "'; $SecurePassword = ConvertTo-SecureString -AsPlainText $PlainPassword -Force;"
+ "$mycred = New-Object System.Management.Automation.PSCredential -ArgumentList $Username, $SecurePassword;";
//creds += "$session = New-PSSession -ComputerName " + domain + " -Credential $mycred;";
String[] args = new String[] { "powershell", creds};
execRemote(args);
return creds;
}
private void execRemote(String[] arguments) throws IOException {
ProcessBuilder builder = new ProcessBuilder(arguments);
builder.redirectErrorStream(true);
Process process = builder.start();
doProcessIO(process);
}
// Do the IO for a passed process
private void doProcessIO(Process p) throws IOException {
p.getOutputStream().close();
String line;
System.out.println("Output:");
BufferedReader stdout = new BufferedReader(new InputStreamReader(
p.getInputStream()));
while ((line = stdout.readLine()) != null) {
System.out.println(line);
}
stdout.close();
System.out.println("Error:");
BufferedReader stderr = new BufferedReader(new InputStreamReader(
p.getErrorStream()));
while ((line = stderr.readLine()) != null) {
System.out.println(line);
}
stderr.close();
System.out.println("Done");
}
public static void main(String[] args) throws IOException {
String ip_add = "192.168.193.101";
String user = "gs-259412";
String pass = "Windows412";
PowerShellSession psSession = new PowerShellSession();
String credentials = psSession.getCredentials(ip_add, user, pass);
psSession.targetIpAddress = ip_add;//;
String cmdd = "New-LocalUser -Name \"User02\" -Description \"Description of this account.\" -NoPassword";//"Get-Culture";
if(!credentials.equals("")) {
psSession.exec(cmdd, credentials);
System.out.println("Finished PowerShell remote session.");
}
psSession.close();
}
}
Output of this program :
Output:
Error:
Done
Output:
A positional parameter cannot be found that accepts argument 'of'.
+ CategoryInfo : InvalidArgument: (:) [New-LocalUser], ParameterBindingException
+ FullyQualifiedErrorId : PositionalParameterNotFound,Microsoft.PowerShell.Commands.NewLocalUserCommand
+ PSComputerName : 192.168.193.131
Error:
Done
Finished PowerShell remote session.
I tried this link also enter link description here

runtime.exec(batchCommand) - Issues with Space in folder

Below method return me below path
Output - "C:\ProgramData\MySQL\MySQL Server 5.5\bin\"
private String getPath() {
String mysqlpath = "";
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection(dbUrl, user, password);
Statement stmt = con.createStatement();
ResultSet res = stmt.executeQuery("select ##datadir");
while (res.next()) {
mysqlpath = res.getString(1);
}
mysqlpath = mysqlpath.replace("\\Data", "\\bin").replace("\\", "\\\\");
System.out.println("Mysql path is :" + mysqlpath);
} catch (Exception ee) {
System.out.println(ee);
}
return mysqlpath;
}
Now i run below command to export mysql dump.
Runtime runtime = Runtime.getRuntime();
Process p = runtime.exec(batchCommand);
batchCommand - "C:\ProgramData\MySQL\MySQL Server 5.5\bin\mysqldump" -h localhost --port 3306 -u root --password=root123 --add-drop-database -B accountingbook -r "E:\softwares\Tomcat_accountingBook\webapps\accountingbookaccountingbook-localhost-(02-08-2017).sql"
Exception - java.io.IOException: Cannot run program ""C:\ProgramData\MySQL\MySQL": CreateProcess error=2, The system cannot find the file specified
I also tried below, but same issue:-
1.) Process p = runtime.exec(batchCommand.split(" "));
2.) Adding double quotes like "C:\ProgramData\MySQL\MySQL Server 5.5\bin\"
Problem is it breaks as soon as it encounters space.
From the Exception, it looks like JVM is not able to find MYSQL executable file at the location given.
This can be due to "\" file separator. Try using "\\" to separate your paths. Then your path would be : "C:\\ProgramData\\MySQL\\MySQL.
I'v written one class this might help you click here
public class RuntimeExample {
private final String commandCode = "cmd /c";
private final Scanner scanner = new Scanner(System.in);
private Process process;
private BufferedReader reader;
private String input = "";
private final String defaultCode = "help";
public RuntimeExample() {
UserInput();
}
private void UserInput() {
System.out.println("Enter command (ex: ipconfig)");
input = scanner.nextLine();
if (input.isEmpty()) {
System.out.println("You didn't give any command please take a look at these available Commands." + "\n");
sendCommand(defaultCode);
} else {
sendCommand(input);
}
}
private void sendCommand(String command) {
try {
process = Runtime.getRuntime().exec(commandCode + " " + command);
reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
showResult(line);
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
private void showResult(String result) {
System.out.println(result + "\n");
}
public static void main(String[] args) {
new RuntimeExample();
}
}

How to restore a MySQL database backup using Java

I was able to create a backup of my current mysql database as .SQL file using the mysqldump.exe with the help of the following java code.
Process runProcess = Runtime.getRuntime().exec("C:\\SCM Files\\SQL Backup\\mysqldump.exe -uroot -p123 rr -r\"C:\\SCM Files\\SQL Backup\\RR.sql");
Now I want to restore this same .SQL Backup file to mysql database using java code similar to above on the event of a button clicked.
Thanks a lot :)
So now I tried this ;
Process runProcess = Runtime.getRuntime().exec("C:\\SCM Files\\SQL Backup\\mysqldump.exe -uroot -p123 rr < C:\\SCM Files\\SQL Backup\\RR.sql");
Still it didn't work :/
public static boolean restoreDB(String dbName, String dbUserName, String dbPassword, String source) {
String[] executeCmd = new String[]{"mysql", "--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 ex) {
ex.printStackTrace();
}
return false;
}
source example : "E:\\My Backup\\Test\\file.sql"
Runtime.getRuntime().exec("mysql -u username -ppassword database_name FILE.sql")
This statement will regenerate database from the file
You have to use java swings where you can design forms. Here is some code which can do that.
import javax.swing.JFrame;
public final class RestoreMySQLDatabase extends JFrame {
private static final long serialVersionUID = 1L;
public static void main(String[] args) {
RestoreMySQLDatabase restoreMySQL = new RestoreMySQLDatabase();
restoreMySQL.setTitle("Restore mysql database");
javax.swing.JButton butRestore = new javax.swing.JButton("Restore");
butRestore.addActionListener(new java.awt.event.ActionListener(){
public void actionPerformed(java.awt.event.ActionEvent event){
try{
Runtime.getRuntime().exec("C:\\SCM Files\\SQL Backup\\mysqldump.exe -uroot -p123 rr -r\"C:\\SCM Files\\SQL Backup\\RR.sql");
javax.swing.JOptionPane.showMessageDialog((javax.swing.JButton)event.getSource(), "Successfully restored");
}catch(java.lang.Exception e){
javax.swing.JOptionPane.showMessageDialog((javax.swing.JButton)event.getSource(), "Not able to restore");
}
}
});
}
}
I tried this code and works as perfect!
String[] restoreCmd = new String[]{"mysql ", "--user=" + DB.DB_USERNAME, "--password=" + DB.DB_PASSWORD, "-e", "source " + pathToFile};
try {
Process runtimeProcess = Runtime.getRuntime().exec(restoreCmd);
int processComplete = runtimeProcess.waitFor();
if (processComplete == 0) {
System.out.println("Done");
} else {
System.out.println("Failed");
}
} catch (Exception ex) {
ex.printStackTrace();
}
You should try DbUnit for backup and restore of database.Here is the demo code for that:
try {
Class.forName(DBDRIVER);
Connection jdbcConnection = DriverManager.getConnection(DBURL, DBUSERNAME, DBPASSWORD);
IDatabaseConnection connection = new DatabaseConnection(jdbcConnection);
connection.getConfig().setProperty(DatabaseConfig.PROPERTY_DATATYPE_FACTORY,
new MySqlDataTypeFactory());
//////// Database backup
ITableFilter filter = new DatabaseSequenceFilter(connection);
IDataSet dataset = new FilteredDataSet(filter, connection.createDataSet());
ExcludeTableFilter excludeFilter = new ExcludeTableFilter();
excludeFilter.excludeTable("DATABASECHANGELOG*");
IDataSet excludedataset = new FilteredDataSet(excludeFilter, dataset);
FlatXmlDataSet.write(excludedataset, new FileOutputStream(backupfilename));
System.out.println("\n Complete backup successful.");
//////// Database backup
//////// Database restore
IDataSetProducer producer = new FlatXmlProducer(new InputSource(restoreFileName));
IDataSet dataSet = new StreamingDataSet(producer);
TransactionOperation operation = new TransactionOperation(DatabaseOperation.INSERT);
operation.execute(connection, dataSet);
//////// Database restore
} catch (DatabaseUnitException e) {
e.printStackTrace();
flag = false;
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
Use the same dump to import like this.
Process runProcess = Runtime.getRuntime().exec("C:\\SCM Files\\SQL Backup\\mysqldump.exe -uroot -p123 rr database_name < "C:\\SCM Files\\SQL Backup\\RR.sql");
For restore use the executeCmd in the form m.Torkashvand provided (array of strings). A working example on how to use these commands from JSP code can be found here
public static void mysqlExport(String host, String port, String user, String password, String dbname, String table, String folder, String query) {
System.out.println("------ Exporting "+dbname+"."+table+" at "+folder+"---------------------------");
try {
String command = "mysqldump --host=" + host + " --port=" + port + " --user=" + user + " --password=" + password + " " + dbname + " " + table + " --where=\"" + query + "\" > " + folder + table + ".sql";
System.out.println(command);
int returnValue = executeCommand(Arrays.asList("mysqldump", "--host="+host, "--port="+port, "--user="+user, "--password="+password, dbname, table, "--where="+query), folder + table + ".sql");
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
public static void mysqlImport(String host, String port, String user, String password, String dbname, String table, String folder) {
System.out.println("------ Importing "+dbname+"."+table+" at "+folder+"---------------------------");
try {
String command = "mysql --host=" + host + " --port=" + port + " --user=" + user + " --password=" + password + " " + dbname + " " + table + " < " + folder + table + ".sql";
System.out.println(command);
int returnValue = executeCommand(new String[]{"mysql", "--host="+host, "--port="+port, "--user=" + user, "--password=" + password, dbname, "-e", "source " + folder + table + ".sql"});
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
public static int executeCommand(String[] commands) throws IOException
{
System.out.println(commands.toString());
Process process = Runtime.getRuntime().exec(commands);
return dumpProcess(process);
}
public static int executeCommand(List<String> commands, String folder) throws IOException
{
ProcessBuilder builder = new ProcessBuilder(commands);
System.out.println(builder.command());
builder.redirectOutput(new File(folder));
Process process = builder.start();
return dumpProcess(process);
}
public static int dumpProcess(Process process) throws IOException
{
int returnValue = -1;
try {
String s = null;
process.waitFor();
returnValue = process.exitValue();
if (returnValue == 0) {
System.out.println("Command successful !!");
BufferedReader stdInput = new BufferedReader(new InputStreamReader(process.getInputStream()));
System.out.println("Here is the standard output of the command:\n");
while ((s = stdInput.readLine()) != null) {
System.out.println(s);
}
} else {
System.out.println("Command failed. Exist Status code = "+returnValue);
BufferedReader stdError = new BufferedReader(new InputStreamReader(process.getErrorStream()));
System.out.println("Here is the standard error of the command (if any):\n");
while ((s = stdError.readLine()) != null) {
System.out.println(s);
}
}
} catch (InterruptedException e) {
e.printStackTrace();
}
return returnValue;
}
This is working code
public class Recover {
final static String filepath = "/home/shubhampanchal/Downloads/backup/configuration_files.sql";
public static void main(String[] args) throws Exception {
try {
String[] restoreCmd = new String[]{"mysql", "-uroot", "-p1", "Student", "-e", "source " + filepath};
Runtime rt =Runtime.getRuntime();
rt.exec(restoreCmd);
System.out.println("Restored successfully!");
} catch(Exception e) {
e.printStackTrace();
}
}
}

Categories

Resources