抛出异常 [com.mysql.jdbc.CommunicationsException:通信 link 由于基础异常而失败:

threw exception [com.mysql.jdbc.CommunicationsException: Communications link failure due to underlying exception:

在我的 java 网络应用程序中,我正在连接到本地 MySQL 数据库。使用 servlet,我获取一个 csv 文件并将数据插入数据库。它连接良好并且正在插入数据,但在每次从 csv 文件插入后它开始逐渐变慢。当它到达 csv 文件中的第 159 行时,它会抛出此异常:

抛出异常

[com.mysql.jdbc.CommunicationsException: Communications link failure due to underlying exception:

java.net.SocketException MESSAGE: Permission denied: connect

堆栈跟踪:

java.net.SocketException: Permission denied: connect

有谁知道为什么它可以正常工作然后变慢直到抛出这个异常?我真的很想知道这个,网上似乎没有任何帮助。对了,我用的是tomcat8.

正如您已经发现的那样,您得到的异常是由于您打开了太多连接而达到了限制。

要正确关闭与数据库的连接,基本上需要三个步骤。

  1. 关闭结果集(如果有的话)
  2. 关闭语句对象
  3. 关闭连接对象

典型的代码如下:

try {
    //your code that is making and using jdbc is here

    //after you finish
    rs.close(); //if a ResultSet was returned
    stmt.close(); //Close Statement
    conn.close(); //Close Connection
}catch(SQLException se){
}catch(Exception e){
}finally{
    //finally block used to close resources if Closing failed above
    try{
       if(stmt!=null)
          stmt.close();
    }catch(SQLException se2){
    }// nothing we can do
    try{
       if(conn!=null)
          conn.close();
    }catch(SQLException se){
       se.printStackTrace();
    }//end finally try
}//end try

有关完整示例,请参阅 this