title: Start and Stop mysql through java
body: <p>I want to start and stop <code>mysql</code> through java program. I tried solution from <a href="https://stackoverflow.com/questions/9990788/start-or-stop-mysql-database-using-java-programming">this</a> question, but it failed to start the mysql. Then I tried using other commands as below:</p>
  
  <pre><code>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();
      }
  }
  </code></pre>
  
  <p>The output of this program is as below:</p>
  
  <pre><code>MySQL server started successfully!
  5.6.16
  MySQL server stopped successfully!
  </code></pre>
  
  <p>But, the process (java code execution) is not getting terminated at the end, it's still <code>Running</code>!</p>
  
  <p>This time it's able to start the process but unable to stop it. The process can be destryed using <code>mysqlProc.destroy()</code> in above code, but isn't that a bad practice?</p>
  
  <p>So, how can I stop the mysql servere that was started using above command?</p>
  
  <p>Or, is there any other way to start and stop mysql through java?</p>