famedoro
famedoro

Reputation: 1241

java mysqldump with where option

I try to use this code, which works on linux command line, under java

mysqldump --where="date>='20180201' AND date<='20180228'" -uuser -ppassword --skip-add-drop-table --no-create-info --no-create-db -B mydb --tables table1 -r /root/Documents/DbBackup/table1.sql

To make it work in java, I use the following code:

public static boolean backupDB(String dbName, String where_filter, String path, String tableName) {
    String executeCmd = "mysqldump --where="+where_filter+" -u" + userName + " -p" + password + " --skip-add-drop-table --no-create-info --no-create-db "+" -B " + dbName +" "+tableName+" -r " + path;

    System.out.println("backupDB "+executeCmd);
    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) {            

    }

    return false;
}

The same command line instruction does not work if the invocation is inside the java code. Where am I wrong? is it possible to redirect an error log to a file?

If I use as where clause--where=date='20180206' it works also under java.

Upvotes: 0

Views: 272

Answers (1)

user12043
user12043

Reputation: 396

You have too many arguments in the command. I think you should use ProcessBuilder instead of Runtime.exec. It takes the command and arguments as an array and this way is safer IMHO. So try this code:

String[] executeCmd = new String[]{
    "mysqldump", "--where=" + where_filter, "-u" + userName, "-p" + password, 
    "--skip-add-drop-table", "--no-create-info", "--no-create-db", "-B", dbName, 
    "--tables", tableName, "--result-file=" + path
};
ProcessBuilder builder = new ProcessBuilder(executeCmd);
builder.redirectErrorStream(true);
Process runtimeProcess;
try {

    runtimeProcess = builder.start();
    InputStream processInputStream = process.getInputStream();
    int processComplete = runtimeProcess.waitFor();
    if (processComplete == 0) {
        System.out.println("Backup created successfully");
        return true;
    } else {
        System.out.println("Could not create the backup");                
    }
    BufferedReader reader = new BufferedReader(new InputStreamReader(processInputStream));
    System.out.println("output: ");
        while (reader.ready()) {
            System.out.println(reader.readLine());
        }
} catch (Exception ex) {

}
return false;

Also try to write the mysqldump command with full path like /usr/bin/mysqldump if works with this, then the mysqldump command is not in the path.

Upvotes: 1

Related Questions