简体   繁体   English

如何关闭断开的 jdbc 连接?

[英]How to close a disconnected jdbc connection?

I am setting up a connection between two servers (One running a jdbc application and second running an oracle DB) using jdbc to query few tables.我正在使用 jdbc 在两台服务器之间建立连接(一台运行 jdbc 应用程序,第二台运行 oracle DB)以查询几个表。

Since these servers reside in two different countries, sometimes there is a disconnect between the two servers.由于这些服务器位于两个不同的国家/地区,因此有时两台服务器之间会断开连接。

When the connection is not established due to IO Error: Network adapter could not establish the connection , the app can retry-establish the connection.由于IO Error: Network adapter could not establish the connection ,应用程序可以重试建立连接。 But once a conn is established, and then there is a disconnect, the application just hangs and doesn't Timeout or come out of the connection.但是一旦建立连接,然后断开连接,应用程序就会挂起并且不会超时或退出连接。

Can anybody please help me out to close or exit such connections?有人可以帮我关闭或退出此类连接吗?

Use the try-with-resources statement使用try-with-resources语句

String user = "user";
String password = "password";
String url = "jdbc:mysql://localhost:3306/database_name";
try (Connection connect = DriverManager.getConnection(url, user, password);
Statement stmt = connect.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM table;");
) {
    while (rs.next()) {
        // TODO
    }
} catch (Exception e) {
    System.out.println(e);
}

You can handle this in the finally block to ensure that the connection is closed in case of both success and exception.您可以在finally块中处理此问题,以确保在成功和异常的情况下关闭连接。 Example code is shared below for your reference.下面共享示例代码供您参考。

import java.sql.*;  
class MysqlConnectionExample{  
    public static void main(String args[]){  
        String jdbcUrl = "jdbc:mysql://localhost:3306/dbName";
        String userName = "userName";
        String password = "password";
        String driverName = "com.mysql.jdbc.Driver";
        Connection con= null;
        Statement stmt = null;
        try{  
            // Create connection
            Class.forName(driverName);  
            con = DriverManager.getConnection(jdbcUrl, userName, password);  
            stmt = con.createStatement();  
            ResultSet rs = stmt.executeQuery("SELECT * FROM employee");  

            // Iterate over the results
            while(rs.next()) { 
                System.out.println(rs.getInt(1)+"  "+rs.getString(2)+"  "+rs.getString(3));  
            }
        }
        catch(Exception e){ 
            System.out.println(e);
        }  
        finally{
            // Close connection
            con.close();
        }
    }  
}

if you use connection fool, i think it's will be like youre situation.如果您使用连接傻瓜,我认为这会像您的情况一样。 As other answers, i recommend to use 'connection.close()';作为其他答案,我建议使用 'connection.close()'; and it needed, it's better to add 'trasation' scope.它需要,最好添加'trasation' scope。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM