Java等待Mysql连接

标签 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, 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 数据库服务器未运行,因此我的应用无法打开连接,我该如何让我的应用等待连接建立?

最佳答案

为了让您的 Connect 方法在实际获得连接之前不返回,您需要用循环包围现有的 try-block。像这样:

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);
    }
}

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

关于Java等待Mysql连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37953850/

相关文章:

java - 从多个表中获取 count(*) 值

java - 我的 Web 应用程序中 C3P0 的实现是否正确?这种实现方式有哪些优点和缺点?

mysql - 如何从 MySQL 中的相同数据更新字段

mysql - 通过连接收集多列聚合数据

java - 如何在swing中为视频制作叠加层

java - riak mapreduce 对 java 中响应大小的限制

java - 访问抽象类方法

mysql - 没有信息插入数据库中的表中

java - 如何减去两个日期(在jlabel中设置)

java - 如何生成具有交替颜色的 Jlist