如何关闭断开的jdbc连接?

问题描述 投票:1回答:3

我正在使用jdbc查询两个表(在一个服务器上运行jdbc应用程序,第二个服务器上运行oracle DB)之间建立连接。由于这些服务器位于两个不同的国家/地区,因此有时两台服务器之间会断开连接。当由于“ IO错误:网络适配器无法建立连接”而无法建立连接时,该应用程序可以重试conn的建立。但是一旦建立了conn,然后断开连接,应用程序就会挂起,并且不会超时或退出连接。有人可以帮我关闭或退出此类连接吗?

java ojdbc
3个回答
1
投票

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

0
投票

您可以在finally块中进行处理,以确保成功和异常时都关闭连接。下面共享示例代码供您参考。

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

0
投票

如果您使用连接傻瓜,我认为情况会与您一样。作为其他答案,我建议使用'connection.close()';并且它需要,最好添加“事务”范围。

© www.soinside.com 2019 - 2024. All rights reserved.