Database Operations in Java are frequent. Many users are often inaccurate in processing database operations. They can only ensure that the program runs normally, however, many of them do not release resources or do not properly release resources. When there is a problem, they do not know what is going on! Here is a simple example of using JDBC to operate databases. We hope to have some reference value. For convenience, we can connect to the factory through the database.
Code for connecting Factory: http://blog.csdn.net/treeroot/archive/2004/09/24/115372.aspx
Let's take a look at the following code. Do you think there is a problem?
Try {
Connection conn = ConnectionFactory_JDBC2.getConnection ();
Statement state = conn. createStatement ();
ResultSet rs = state.exe cuteQuery ("select * from table ");
// Process data here
Rs. close ();
State. close ();
Conn. close (); // some do not even have this sentence
}
Catch (SQLException e ){
// You can handle it yourself or throw it.
}
Here is an alternative implementation:
Connection conn = null;
Statement state = null;
ResultSet rs = null;
Try {
Conn = ConnectionFactory_JDBC2.getConnection ();
State = conn. createStatement ();
Rs = state.exe cuteQuery ("select * from table ");
// Process data
}
Catch (SQLException e ){
// You can handle it yourself or throw it.
}
Finally {
If (rs! = Null ){
Try {rs. close ();} catch (SQLException e ){}
}
If (state! = Null ){
Try {state. close ();} catch (SQLException e ){}
}
ConnectionFactory_JDBC2.closeConnection (conn );
}
This implementation seems to be more complicated, but the reliability is higher. Although the implementation of the first piece of code is generally not a problem, it is really difficult to have a problem (sometimes it is not easy to make Windows blue screen), but it is strongly recommended to release your resources through finally, rather than let the potential danger exist!