Sean
Sean

Reputation: 725

JDBC: Catch "SQLException: I/O Error: Connection reset caused" by "SocketException: Connection reset"

My code establishes JDBC connection and repeatedly queries Microsoft SQL SMS. However, sometimes I get the error:

"Exception in thread "main" java.sql.SQLException: I/O Error: Connection reset" followed by "Caused by: java.net.SocketException: Connection reset" enter image description here

Here is what my code looks like:

public static void main(String[] args){
    ...
    // Establish JDBC connection
    Class.forName(DRIVER);
    Connection conn = DriverManager.getConnection(URL, USER, PASS);
    Statement stmt = conn.createStatement(); 
    ...
    // Perform SQL query
    for(int i=0; i<size; i++)
        functionA(stmt); // <--line 62
    ...
}

public static void functionA(Statement stmt){
    String aql = "INSERT INTO...";
    stmt.executeUpdate(sql); // <-- line 105
}

I query the database in order to test some function unrelated to the data. Hence, I want my program to automatically re-establish the connection when the exception is thrown so I can leave it running by itself.

My questions are: 1)Can I re-establish JDBC connection in try...catch? 2)If so, which exception to catch and where to catch it? 3)What should I place in catch?

Upvotes: 1

Views: 5042

Answers (1)

aleroot
aleroot

Reputation: 72676

In the case you want to catch the exception that you listed in the question, you will need to catch the SQLException, for example :

  // Perform SQL query
    for(int i=0; i<size; i++) {
        try {
        functionA(stmt); // <--line 62
        } catch(SQLException e) {
          System.out.println(e.getMessage());
          //You can add here your recovery logic ...
        }
    }

And yes, you can try to reestablish the connection after the exception putting in place a kind of reconnect mechanism in the catch block ...

In the case you want to check the inner exception that caused the SQLException you can check the that with getCause() :

        } catch(SQLException e) {
          if(e.getCause() instanceof SocketException) {
          //You can add here your recovery logic ...
          }
        }

Upvotes: 2

Related Questions