Search code examples
javamysqlprocessbuilder

Execute MySQL commands in Java ProcessBuilder on Windows


I'm trying to execute some MySQL commands from Java ProcessBuilder on WINDOWS and I faced some problems. At the moment, what I want to do is to show databases but in the near future I'm going to use dump etc. So this is the way it should be.

Here is my code:

try {

//  Process process = Runtime.getRuntime().exec("cmd /c C:/\"Program files\"/MySQL/\"MySQL Server 8.0\"/bin/mysql -uroot -pMYPASS -e \"show databases;\""); 
//  IT DIDN'T WORK EITHER.

    ProcessBuilder coolBuilder = new ProcessBuilder(new String[]{"cmd", "/c", "C://\"Program files\"/MySQL/\"MySQL Server 8.0\"/bin/mysql -u root -pMYPASS -e \"show databases;\""});
    Process process = coolBuilder.start();

    int errCode = process.waitFor();
    if (errCode != 0) {
        System.out.println("errCode = " + errCode);
        errorList.add(ErrorEnum.ERROR_OCCURED_WHILE_INSIDE_SHELL.toString());
    }

    for (String s : output(process.getErrorStream())) {
        if (!s.contains("Warning")) {
            errorList.add(s);
            return errorList;
        }
    }

    return output(process.getInputStream());

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

Here is what I get:

C://Program files/MySQL/MySQL Server 8.0/bin/mysql  Ver 8.0.20 for Win64 on x86_64 (MySQL Community Server - GPL)
Copyright (c) 2000, 2020, Oracle and/or its affiliates. All rights reserved.
Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.
Usage: C://Program files/MySQL/MySQL Server 8.0/bin/mysql [OPTIONS] [database]
  -?, --help          Display this help and exit.
  -I, --help          Synonym for -?
  --auto-rehash       Enable automatic rehashing. One doesn't need to use
                      'rehash' to get table and field completion, but startup



...

errCode = 1

Any suggestions where I'm doing it wrong?


Solution

  • I couldn't reproduce your problem. I suspect you might have an odd character in your password that the Windows command prompt isn't keen on.

    Have you tried to execute the mysql executable directly rather than via cmd.exe, i.e. by using something like the following?

            ProcessBuilder coolBuilder = new ProcessBuilder(new String[]{"C://Program files/MySQL/MySQL Server 8.0/bin/mysql", "-u", "root", "-pMYPASS", "-e", "show databases;"});
            Process process = coolBuilder.start();
    

    This way you don't need to quote all of the arguments.