1

In my java web application, I'm connecting to a local MySQL database. Using a servlet I'm taking a csv file and inserting the data into the database. It connects fine and is inserting data, but it starts to progressive slow down after each insert it does from the csv file. When it gets to about row 159 in the csv file it throws this exception:

threw exception

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

java.net.SocketException MESSAGE: Permission denied: connect

STACKTRACE:

java.net.SocketException: Permission denied: connect

Does anyone know why it would be working fine and then slow down until it throws this exception? I'm really scratching my head about this and nothing online seems to be helping. By the way, I'm using tomcat8.

TommCatt
  • 5,498
  • 1
  • 13
  • 20
Stryker
  • 47
  • 1
  • 5
  • 1
    are you re-using your connections, closing them or just letting that remain in memory – Scary Wombat Apr 15 '15 at 04:57
  • I think @ScaryWombat is on the mark, q.v. [this post](http://stackoverflow.com/questions/6865538/solving-a-communications-link-failure-with-jdbc-and-mysql). Please try restarting your MySQL. If that fixes the problem, then you likely have a connection pool problem. – Tim Biegeleisen Apr 15 '15 at 05:01
  • I think you are correct, the number of connections grows when I'm running the program and they don't seem to be closing. I'm calling connection.close() after I do the insert, but that doesn't seem to be closing the connection. Why wont they close if I'm calling connection.close()? – Stryker Apr 15 '15 at 06:08

1 Answers1

1

As you have already discovered the exception you get comes from the reason that you open so many connections that the limit is reached.

To properly close connections to a db there are basically three steps.

  1. Close ResultSet (if there is any)
  2. Close Statement Object
  3. Close Connection Object

Typical code is something like the following:

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

For a complete example see this

MaVRoSCy
  • 17,747
  • 15
  • 82
  • 125