Improve the reliability of database operations

xiaoxiao2021-03-06  55

The database operation in Java is more frequent. Many people often get accurate when dealing with database operations. They can only guarantee that there is no problem in running the program, but there are no resource or no correct release resources, wait until there is a problem. Know what happened! Here is a simple example of the JDBC operating database, it is desirable to have a certain reference value, for convenience, access to the factory connection plant. Code for connecting factory: http://blog.9cbs.net/treeroot/archive/2004/09/24/115372.aspx

Let's take a look at the code below. Do you think there is a problem?

try {Connection conn = ConnectionFactory_JDBC2.getConnection (); Statement state = conn.createStatement (); ResultSet rs = state.executeQuery ( "select * from table"); // this data processing rs.close (); state.close ( ); Conn.close (); // Some even this sentence is not} catch (SQLEXCEPTION E) {// Here you can handle it yourself, or throw}

Here is an alternative implementation:

Connection conn = null; Statement state = null; ResultSet rs = null; try {conn = ConnectionFactory_JDBC2.getConnection (); state = conn.createStatement (); rs = state.executeQuery ( "select * from table"); // process Data} Catch (SQLEXCEPTION E) {// You can handle yourself, or throw} finally {if (rs! = Null) {Try {r. cclose ();} catch (sqlexception e) {}}} ! = 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 code is generally not there, it is really difficult to have problems (sometimes I want Windows Lan screen is really not easy), but still It is highly recommended to release your resources through Finally, do not let potential dangers exist!

转载请注明原文地址:https://www.9cbs.com/read-113513.html

New Post(0)