简体   繁体   中英

MySQL database restore code using java is not working and makes application not responding

Here is my code for mysql database restore code .when i tried this code app works without exception but application get hangs and database is not restored ..please help me

String databaseName = "sample"; //database name
String userName = "root"; // MySQL username
String password = ""; // MySQL password
int processComplete; // this variable for verify the process

String[] executeCmd = new String[]{"C:\\wamp\\bin\\mysql\\mysql5.5.24\\bin\\mysql",
        databaseName, "-u" + userName, "-p" + password, "-e", " source D:/data.sql"};

System.out.println(executeCmd);
Process runtimeProcess = Runtime.getRuntime().exec(executeCmd);// execute the command
processComplete = runtimeProcess.waitFor();
System.out.println(processComplete);

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");
}

I suspect that the last parameter is been mishandled

String[] executeCmd = new String[]{
    "C:\\wamp\\bin\\mysql\\mysql5.5.24\\bin\\mysql", 
    databaseName, 
    "-u" + userName, 
    "-p" + password, 
    "-e", 
    " source D:/data.sql" }

It should probably look more like...

String[] executeCmd = new String[]{
    "C:\\wamp\\bin\\mysql\\mysql5.5.24\\bin\\mysql", 
    databaseName, 
    "-u" + userName, 
    "-p" + password, 
    "-e", 
    "source", 
    "D:/data.sql" }

Each element in the array will be a separate argument passed to the command, this allows you the flexibility of passing arguments that have spaces in them without need to first escape them using quotes

You should consider using ProcessBuilder instead of trying to build the Process yourself, apart from allowing you to re-direct the error stream to the input stream, it also allows you to specify the starting context for the process.

You should also be reading the output of the process (via it's InputStream ) which would possibly highlight issues and may also allow the process to exit (as some process won't exit until there stdout is read completely)

For example: How do I execute Windows commands in Java?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM