简体   繁体   中英

How to start MySQL via Java on Windows and return when its up?

How can I start MySQL in a windows environment and return to the commandline when the startup finished and it is running?

If I do a

mysqld --defaults-file=... --console

the server starts but mysqld blocks while it is running.

Background for this requirement is that I want to start MySQL from a Java-Program (using Runtime.getRuntime().exec(...) ) and run another program when MySQL is ready.

I solved this by running the command in its own Thread and wait until I can connect to the server:

Thread runningThread = new Thread() {
  @Override
  public void run() {
    String[] cmdArray = new String[3];
    cmdArray[0] = "mysqld.exe";
    cmdArray[1] = "--defaults-file=./my.ini";
    cmdArray[2] = "--console";
    try {
      Process proc = Runtime.getRuntime().exec(cmdArray);

      // read results
      BufferedReader br = new BufferedReader(new InputStreamReader(proc.getInputStream()));
      String line;
      while ((line = br.readLine()) != null) {
        System.out.println(line);
      }

      br = new BufferedReader(new InputStreamReader(proc.getErrorStream()));
      while ((line = br.readLine()) != null) {
        System.out.println(line);
      }
      try {
        proc.waitFor();
      } catch (InterruptedException ex) {
        ex.printStackTrace();
      }
    } catch (IOException ex) {
      ex.printStackTrace();
    }
  }
};
runningThread.start();
while(!isMySQLRunning()) {
  System.out.println("waiting for MySQL to start...");
}

// ...

private static boolean isMySQLRunning() {
  String[] cmdArray = new String[7];
  cmdArray[0] = "mysqladmin.exe";
  cmdArray[1] = "-u";
  cmdArray[2] = "root";
  cmdArray[3] = "-pMyPassord";
  cmdArray[4] = "-P";
  cmdArray[5] = "3306";
  cmdArray[6] = "status";
  Vector<String> res = runCommand(cmdArray); // runCommand(): see above
  if (res.size() > 0 && res.get(0).contains("Can't connect to MySQL server")) {
    System.out.println("MySQLis not running.");
    return false;
  } else if (res.size() > 0 && res.get(0).contains("Uptime")) {
    System.out.println("MySQLis running.");
    return true;
  }
  System.out.println("MySQLis not running.");
  return false;
}

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