Database Connection is an object that we usually create connection, statement, and resultset. New users may use the following:
Connection connection = drivermanager. getconnection ("Database URL"); Statement statement = connection. createstatement (); // The JDBC code resultset = ............ Resultset. Close (); statement. Close (); connection. Close ();
The above method is incorrect. Because if you create a connection with a databaseGetconnection () andWhen an exception (sqlexception) is thrown between close (), close () is ignored completely.
The correct way to release database connections and JDBC resources is to put close () in the Finally block for try-catch-finally exception handling. Modify as follows:
Connection connection = NULL; Statement statement = NULL; resultset = NULL; try {connection = drivermanager. getconnection ("Database URL"); Statement = connection. createstatement (); // The JDBC code resultset = ...... ......} Catch (sqlexception e ){......} Finally {If (resultset! = NULL) {resultset. Close ();} If (statement! = NULL) {statement. Close ();} If (statement! = NULL) {connection. Close ();}}
However, close may also throw a sqlexception exception. When the program runs to resultset. Close (), it throws a sqlexception exception, and the next statement is ignored. Therefore, the safest way is to use try-catch for each close (), as shown below:
Connection connection = NULL; Statement statement = NULL; resultset = NULL; try {connection = drivermanager. getconnection ("Database URL"); Statement = connection. createstatement (); // follow the JDBC code resultset = ............ Resultset = ...... } Catch (sqlexceptione ){...... } Finally {try {resultset. close ();} catch (sqlexceptione) {} Try {statement. close ();} catch (sqlexceptione) {} Try {connection. close () ;}catch (sqlexceptione ){}}}