【问题标题】:Start and Stop mysql through java通过java启动和停止mysql
【发布时间】: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


    【解决方案1】:

    进程仍然存在的原因是你永远不会终止它。如果您以上述方式使用 Java Process API,则子进程 (MySQL) 将等待指示做什么。这是有道理的,因为大多数时候,Java 代码都希望与孩子对话并通过 stdio 交换数据。

    在您的情况下,这没有任何意义:您已经通过 JDBC 进行通信,因此 stdio 管道只是闲逛,让孩子保持活力。当 Java 停止时,大多数孩子都会死去,但显然 MySQL 更有弹性。

    在这种情况下调用destroy是安全的,因为即使主进程意外崩溃,MySQL也不能破坏数据。不过,这不是一个好习惯。

    解决您的问题:

    1. 使用将 MySQL 作为守护程序启动的 shell 脚本包装器。该脚本应立即启动并返回,让 MySQL 服务器在后台运行。
    2. 确保正确处理 stdio。如果您将这些管道留在周围,孩子可能会挂起(例如,出现错误时)。
    3. 您最终必须调用Process.waitFor() 以确保正确清理子进程。

    【讨论】:

      猜你喜欢
      • 2018-05-26
      • 2016-12-19
      • 1970-01-01
      • 2012-07-31
      • 2013-07-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-01
      相关资源
      最近更新 更多