我正在设置两个服务器(一个运行jdbc应用程序,另一个运行oracle DB)之间的连接,使用jdbc查询几个表。
由于这些服务器位于两个不同的国家/地区,因此有时两台服务器之间会出现连接中断。
当由于IO Error: Network adapter could not establish the connection而无法建立连接时,应用程序可以重新尝试建立连接。但是,一旦建立了连接,然后断开连接,应用程序就会挂起,并且不会超时或退出连接。
有人能帮我关闭或退出这样的连接吗?
发布于 2019-10-29 14:11:47
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);
}发布于 2019-10-29 13:59:24
您可以在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();
}
}
}发布于 2019-10-29 15:21:22
如果你使用连接笨蛋,我想这将是你的情况。作为其他答案,我建议使用'connection.close()';如果需要,最好添加'trasation‘作用域。
https://stackoverflow.com/questions/58601971
复制相似问题