When you do a Java database query, you will first create a database connection according to the standard method in many books, and then call the query on the connection, turn off the connection immediately after use. Later, I feel that if I want to query frequently, then I have to establish a connection, turn off the connection, and have a waste of resources. Usually use the connection pool in this case, such a plurality of queries can share the connection, and the establishment and closing the connection is only implemented at the beginning and end of the program, which greatly improves efficiency.
When I did a database query in the past few days, I encountered a situation between the two previous types, and both need to query data, but only one connection is required. I created a connection in the beginning of the program, and the query code in the future is as follows:
PREPAREDSTATEMENT Statement;
Try {
/ / Database operation here
STATEMENT.CLOSE ();
}
Catch (Exception E) {
System.err.Println (e);
}
Each query code is like this, because there will be no multiple queries, so I think this is correct. If the "Database Operation" section of the above code will not be wrong, such code is indeed correct, but if an exception occurs, then the statement.close () is not executed, so that the statement still occupies the database connection. Can not be done in the future query. This requires us to close the statement correctly. After referring to the approach of the online approach, I use the following code:
PREPAREDSTATEMENT Statement;
Try {
/ / Database operation here
}
Catch (Exception E) {
System.err.Println (e);
}
Finally {
Try {
STATEMENT.CLOSE ();
}
Catch (Exception E1) {
System.err.println (E1);
}
}
The part of FINALLY is always to be executed, so put the statement.close () in the finally, and Statement.close () itself will throw an exception, so use a try ... catch statement.
This approach ensures that the query can still close Statement correctly, it is a better practice. But if Statement.close () is wrong, then it will still cause future queries that cannot be executed, so the best way is to use the connection pool to manage the connection.