【发布时间】:2014-02-27 08:06:57
【问题描述】:
我想通过java程序启动和停止mysql。我尝试了this问题的解决方案,但无法启动mysql。然后我尝试使用以下其他命令:
private static String commandStart = SQL_INSTALL_DIR + "/bin/mysqld";
private static String commandStop = SQL_INSTALL_DIR + "/bin/mysqld -u root shutdown";
public static void main(String[] args) {
Connection con = null;
Statement st = null;
ResultSet rs = null;
startMysql();
String url = "jdbc:mysql://localhost:3306/testdb";
String user = "testuser";
String password = "test623";
try {
con = DriverManager.getConnection(url, user, password);
st = con.createStatement();
rs = st.executeQuery("SELECT VERSION()");
if (rs.next()) {
System.out.println(rs.getString(1));
}
} catch (SQLException ex) {
Logger lgr = Logger.getLogger(Main.class.getName());
lgr.log(Level.SEVERE, ex.getMessage(), ex);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
try {
if (rs != null) {
rs.close();
}
if (st != null) {
st.close();
}
if (con != null) {
con.close();
}
stopMysql();
} catch (SQLException ex) {
Logger lgr = Logger.getLogger(Main.class.getName());
lgr.log(Level.WARNING, ex.getMessage(), ex);
}
}
}
private static void startMysql() {
try {
mysqlProc = Runtime.getRuntime().exec(commandStart);
System.out.println("MySQL server started successfully!");
} catch (IOException e) {
e.printStackTrace();
}
}
private static void stopMysql() {
try {
Runtime.getRuntime().exec(commandStop);
System.out.println("MySQL server stopped successfully!");
} catch (IOException e) {
e.printStackTrace();
}
}
这个程序的输出如下:
MySQL server started successfully!
5.6.16
MySQL server stopped successfully!
但是,进程(java 代码执行)最终并没有终止,它仍然是Running!
这一次它能够启动进程但无法停止它。可以在上面的代码中使用mysqlProc.destroy() 来破坏该过程,但这不是一个不好的做法吗?
那么,如何停止使用上述命令启动的 mysql servere?
或者,有没有其他方法可以通过java来启动和停止mysql?
【问题讨论】:
标签: java mysql-connector mysql