MoienGK
MoienGK

Reputation: 4654

Fail to call mysqldump from java in linux

This is the code :

public static File backupDB() throws IOException {

    File file = null;

    file = new File("BKUP_DB_"
            +   Calendar.getInstance()).replace("/", "-") + ".sql");

    String executeCmd = "mysqldump -u " + "dbUserName" + " -p" + "dbPassword"
    + " " + "dbName" + " > " +file.getPath();



    Process runtimeProcess;
    try {

        runtimeProcess = Runtime.getRuntime().exec(executeCmd);
        int processComplete = runtimeProcess.waitFor();

        if (processComplete == 0) {
            System.out.println("Backup created successfully");
            runtimeProcess.destroy();
            return file;
        } else {

            System.out.println("Could not create the backup");
        }

    } catch (Exception ex) {
        ex.printStackTrace();

    }

    return file;
}

i have tried using the full path of mysqldump like /usr/bin/mysqldum but nothing seems to be working, i am suspecting permission issues about linux. do you have to be root to be able to create a mysql backup? if not, what is the problem with this code ? if yes what is the problem with linux :D? how can i fix this problem. thank you.

Upvotes: 2

Views: 1534

Answers (1)

Ernest Friedman-Hill
Ernest Friedman-Hill

Reputation: 81684

The metacharacter ">" is implemented by the shell; no shell is involved in running a program with Runtime.exec() so the last two arguments to mysqldump are garbage. Use the array argument form of Runtime.exec(); pass "/bin/sh" as the first argument, "-c" as the second, and your command line as the third; that way the shell metacharacters will be interpreted by /bin/sh.

Upvotes: 12

Related Questions