Search code examples
javamysqlaccess-denied

CreateProcess error=5, Access is denied while mysql database backup using processbuilder in java


I am trying to backup MySQL DB using ProcessBuilder in Java but, I get this error.

"!Cannot run program "C:\Program Files\MySQL\MySQL Server 5.5\bin": CreateProcess error=5, Access is denied".

Here is my Code.

public static String backupDb() {
    String resp=null;
    try {
        System.out.println("Started........");
        ProcessBuilder builder = new ProcessBuilder("C:\\Program Files\\MySQL\\MySQL Server 5.5\\bin", "mysqldump -u root -pmypass mydb> c:\\backup\\mybackup.sql");
        builder.redirectErrorStream(true);
        Process p = builder.start();
    } catch(Exception e) {
        resp="!"+e.getMessage();
    }
    return resp;
}

Where could I be going wrong?


Solution

  • There are a few things you have to do for this to work:

    1. open a terminal/console to run the mysql dump command in, else the redirection operator(>) won't work.
    2. check that required folders from file path exist. For instance, if you want to backup your database in C:\\foo\bar\foobar\backup.sql but one of the C:\\foo, C:\\foo\\bar, C:\\foo\\bar\\foobar folders doesn't exist, you'll get an error
    3. Adjust the path to mysqldump so that folder names containing white spaces are wrapped in " ", else you'll get awkward errors, such as : 'C:\Program' is not recognized as an internal or external command
    4. read the error stream in case of error, else your process will hang. A return value of 0 indicates success.

    Here is a tested version including all the things above. I'm passing the filepath as a parameter, because it's more flexible this way.

    public static void backupDb(final String mysqlDumpFilePath)
        throws IOException, InterruptedException {
    
        String folderPath = mysqlDumpFilePath.substring(0, mysqlDumpFilePath.lastIndexOf("\\"));
        File folder = new File(folderPath);
        if (!folder.exists()) {
            folder.mkdirs(); // 2
        }
        File f = new File(mysqlDumpFilePath);
        ProcessBuilder builder = new ProcessBuilder("cmd.exe", "/c", "C:\\\"Program Files\"\\MySQL\\\"MySQL Server 5.5\"\\bin\\mysqldump -u root -pmypass mydb > "
            + f.getAbsolutePath()); //1 & 3
    
        Process exec = builder.start();
        int retCode = exec.waitFor();
        if (retCode != 0) { //4
            // something went wrong
            InputStream errorStream = exec.getErrorStream();
            byte[] buffer = new byte[errorStream.available()];
            errorStream.read(buffer);
    
            System.out.println(new String(buffer));
        }
    
    }