Java正在等待Mysql连接

Java正在等待Mysql连接,java,mysql,swing,connection,wait,Java,Mysql,Swing,Connection,Wait,我的应用程序使用Mysql连接,这是通过以下代码获得的: public static void Connect(){ try { Class.forName("com.mysql.jdbc.Driver").newInstance(); String url = "jdbc:mysql://" + host + ":" + port + "/"+ db; ct = DriverManager.getConnection(url, u

我的应用程序使用Mysql连接,这是通过以下代码获得的:

public static void Connect(){
    try
    {
        Class.forName("com.mysql.jdbc.Driver").newInstance();
        String url = "jdbc:mysql://" + host + ":" + port + "/"+ db;
        ct = DriverManager.getConnection(url, user, pass);
        st = ct.createStatement();
        System.out.println("Csatlakozva....\n");
    }   
    catch (InstantiationException e) 
    {
        Main.textArea.setText("Error : Instantiation!");
        //System.err.println("Error : Instantiation");
        e.printStackTrace();
    }
    catch (IllegalAccessException e) 
    {
        Main.textArea.setText("Error : Illegális Behatolás!");
        //System.err.println("Error : Illegális Behatolás!");
        e.printStackTrace();
    } 
    catch (ClassNotFoundException e)
    {
        Main.textArea.setText("Error : Class Nem Található!");
        //System.err.println("Error : Class Nem Található!");
        e.printStackTrace();
    } 
    catch (SQLException e) 
    {
        Main.textArea.setText("Error : Adatbázis Nem Található!");
        //System.err.println("Error : Adatbázis Nem Található!");
        e.printStackTrace();
    }
}

如果MySQL数据库服务器未运行,因此我的应用程序无法打开连接,如何使我的应用程序等待连接建立?

我猜您有线程问题

您可以将JDBC连接代码放入新线程

private class JDBCConnection extends Thread{

public void run(){
....
}

}

为了让您的
Connect
方法在实际获得连接之前不返回,您需要用一个循环包围现有的try块。大概是这样的:

public static void Connect() throws InterruptedException { // It isn't nice to block forever, so we will allow for interrupt
    for (;;) {
        try
        {
            Class.forName("com.mysql.jdbc.Driver").newInstance();
            String url = "jdbc:mysql://" + host + ":" + port + "/"+ db;
            ct = DriverManager.getConnection(url, user, pass);
            st = ct.createStatement();
            System.out.println("Csatlakozva....\n");
            return; // Break out of loop because we got a connection - no exception was thrown
         }   ...

         // One of the exceptions happened. We will continue to loop so
         // we try to connect again until we are successful. We don't want
         // to retry too fast, because painful experience has taught us that
         // bad things can happen (full logs, 100% CPU, etc.).
         Thread.sleep(1);
    }
}

探索和理解这些低级问题是一个很好的练习。然而,我只想在这里指出,(根据我的经验)大多数应用程序都使用连接池来管理数据库连接。一般来说,连接池将提供阻塞功能(通常在有限的时间内),直到可以获得连接。换句话说,连接池不仅允许重用以前创建的连接,还允许在必要时处理连接重试。

能否在代码中添加注释以显示等待的位置?这是本地还是远程MySQL实例?你用的是什么手术系统?那么,你的确切问题是什么?你想发生什么?@Michael Markidis我想做的是…这是我的连接代码…我想如果mysql没有运行,所以我的应用程序无法打开连接,我的应用程序必须等待连接才能执行某些操作。