2015-11-08 19 views
1

如何在Windows環境中啓動MySQL並在啓動完成並返回命令行時運行?如何在Windows上通過Java啓動MySQL並在啓動時返回?

如果我做了

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

服務器啓動,但在運行時的mysqld塊。

此要求的背景是我想從Java程序啓動MySQL(使用Runtime.getRuntime().exec(...)),並在MySQL準備就緒時運行另一個程序。

+0

我會推出一個「開始」,並嘗試在temporized循環 – 2015-11-08 10:09:40

+0

我試圖連接通過運行'cmd/c start/B mysqld ...'但它不起作用... – Benvorth

+3

要啓動MySql服務器,請在命令行中輸入'net start '。 – Marichyasana

回答

1

我解決了這個由自己的線程中運行命令,等待我可以連接到服務器:

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; 
} 
相關問題