Improve Database Operation Reliability

Source: Internet
Author: User

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!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.