Connection express the meaning of a Connection and database link, the underlying operating system has required Socket support Connection is a resource so, now that is a kind of resources required in accordance with the set up, open, use, turn off the use of reasonable order.
Java Database Connection is the basic operation is to conduct a series of basic operations, all the derived operations, such as Statement, PreparedStatement, ResultSet, etc. Connection are derived directly or indirectly.

Connection on how to obtain it?
Method 1, use the DriverManager class to obtain, a prerequisite for database-driven procedures are required in the classpath (ie the use of database links in accordance with the Java program can access to the means).
Connection conn = DriverManager.getConnection ( "jdbc: oracle: thin: @ 192.168.0.1:1521: ORCL", user, pwd);
Two Ways to use a database connection pool to obtain what is database connection pool, the database connection pool is a standard JavaEE container services, such as Webspher, Weblogic, Tomcat, etc., containers set up in advance a number of databases link to the application to use when to borrow, there is also attention to borrow, when to use after the expiry of the application will link back to the database connection pool. (Data source configuration please refer to other documents)
The use of the advantage of connection pooling, you can set up links in advance, reducing access to the database on the relative time.
Access to the database using the connection pool for the link:
InitialContext ctx = new InitialContext ();
DataSource ds = (DataSource) ctx.lookup ( "java: comp / env / jdbc / DataSource");
Connection conn = ds.getConnection ();
Because of the configuration database when the connection pool has been the definition of a URL, user name, password and other information, so at a time when the procedure does not require the use of incoming information.

Connection to the definition of ConnectionManager specialized management database link ConnectionManager usually only one way to call this method will return the instance of a Connection. Connection through the package ConnectionManager can access methods (such as when the development of the use of DriverManager, using the DataSource when a way to use, but do not need to modify other than ConnectionManager code) and the Connection to obtain additional before and after the operation (such as the property for the Connection settings).
The following code is a code sample ConnectionManager:

package com.jpleasure.jdbc.dao;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class ConnectionManager (

public static Connection getConnection () throws DaoException (
Connection conn = null;
try (
conn = DriverManager.getConnection ( "", "", "");
) Catch (SQLException e) (
throw new DaoException ( "can not get database connection", e);
)
return conn;
)
)

If you need to use from the development model to model, only need to modify the above code as follows:
package com.jpleasure.jdbc.dao;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class ConnectionManager (

public static Connection getConnection () throws DaoException (
Connection conn = null;
try (
Context ctx = new InitialContext ();
DataSource ds = (DataSource) ctx.lookup ( "jdbc / dsname");
conn = ds.getConnection ();
) Catch (NamingException e) (
throw new DaoException ( "can not find datasource", e);
) Catch (SQLException e) (
throw new DaoException ( "can not get database connection", e);
)
return conn;
)
)

If you need some pre-configured Connection property can also be set in the code, such as:
package com.jpleasure.jdbc.dao;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class ConnectionManager (

public static Connection getConnection () throws DaoException (
Connection conn = null;
try (
Context ctx = new InitialContext ();
DataSource ds = (DataSource) ctx.lookup ( "jdbc / dsname");
conn = ds.getConnection ();
conn.setAutoCommit (false);
) Catch (NamingException e) (
throw new DaoException ( "can not find datasource", e);
) catch (SQLException e) (
throw new DaoException ( "can not get database connection", e);
)
return conn;
)
)

The definition of property and construction CommonDao usually Ways, CommonDao have a Connection reference. CommonDao all examples of a method call to all have to rely on this Connection. Connection of a required one of the reasons why other methods are all necessary to ensure that if a transaction in the environment (the context), we must ensure that all operations are on a Connection.
Construction methods are usually required to be the type of property for instances of Connection, for example:

package com.jpleasure.jdbc.dao;

import java.sql.Connection;

public class CommonDao (

private Connection conn;

public CommonDao () throws DaoException (
this.conn = ConnectionManager.getConnection ();
)
)

Service methods begin ()
Start a transaction, call the begin method CommonDao after the follow-up operation will be so in a Service environment, or all of the author or full rollback.

commit ()
Submit a Service, we must begin to call in after the call. Mutually exclusive and Ways and rollback.

rollback ()
Rollback a transaction must begin after the method invocation call. And Ways and commit mutex.

Service has two methods of implementation, a single Connection are based on the affairs of another approach is to use containers JTA (Java Transaction API). Should be noted that the first method can be used in any environment, but only for a single database link. The second method of intelligence in support of JTA in Java EE containers to use (such as Websphere, Weblogic, etc., Tomcat does not support the default), but support multiple instances Connection.
The first method code as follows:
package com.jpleasure.jdbc.dao;

import java.sql.Connection;
import java.sql.SQLException;

public class CommonDao (

private Connection conn;

public CommonDao () throws DaoException (
this.conn = ConnectionManager.getConnection ();
)

public void begin () throws DaoException (
if (conn! = null) (
try (
conn.setAutoCommit (false);
) Catch (SQLException e) (
throw new DaoException ( "can not begin transaction", e);
)
) Else (
throw new DaoException ( "connection not opened!");
)
)

public void commit () throws DaoException (
try (
if (conn! = null & &! conn.getAutoCommit ()) (
conn.commit ();
conn.setAutoCommit (true);
) Else (
if (conn == null) (
throw new DaoException ( "connection not opened!");
) Else (
throw new DaoException ( "first begin then commit please!");
)
)
) Catch (SQLException e) (
throw new DaoException ( "can not commit transaction!", e);
)
)

public void rollback () throws DaoException (
try (
if (conn! = null & &! conn.getAutoCommit ()) (
conn.rollback ();
conn.setAutoCommit (true);
) Else (
if (conn == null) (
throw new DaoException ( "connection not opened!");
) Else (
throw new DaoException ( "first begin then rollback please!");
)
)
) Catch (SQLException e) (
throw new DaoException ( "can not rollback transaction!", e);
)
)


)

At our second example of the use of DAO in the introduction how to use the (@ TODO)
Two new DAO, to do a different operation, use the JTA to ensure that integrity matters.

Query methods
CommonDao query methods are perhaps the most commonly used methods, query methods will be required to return the results of the database screen. We generally do not return the value of the use of ResultSet, because ResultSet dependent on Connection, if Connection closed, ResultSet will be no longer valid, so we usually ResultSet into a List back after.
In explaining the methods of inquiry, we will first talk about how the contents of the database on the List, we use a List collection express the results of a query, using a Map of the express line collection, Map of the key that the database table field name , Value of the contents of that database field. Code as follows:
private List convert (ResultSet rs) throws DaoException (

/ / Record list
List retList = new ArrayList ();

try (
ResultSetMetaData meta = rs.getMetaData ();

/ / Column count
int colCount = meta.getColumnCount ();

/ / Each record
while (rs.next ()) (

Map recordMap = new HashMap ();

/ / Each column
for (int i = 1; i <= colCount; i + +) (
/ / Column name
String name = meta.getColumnName (i);
/ / Column value
Object value = rs.getObject (i);
/ / Add column to record
recordMap.put (name, value);
)
/ / Ad record to list
retList.add (recordMap);
)
) Catch (SQLException ex) (
throw new DaoException ( "can not convert result set to list of map", ex);
)
return retList;
)

Sql injection in order to avoid the security problem, we normally use PreparedStatement, when the use of PreparedStatement involves how to set the incoming parameters to the PreparedStatement above, see the following common methods:
private void apply (PreparedStatement pstmt, List params) throws DaoException (
try (
/ / If params exist
if (params! = null & & params.size ()> 0) (
/ / Parameters iterator
Iterator it = params.iterator ();

/ / Parameter index
int index = 1;
while (it.hasNext ()) (

Object obj = it.next ();
/ / If null set ""
if (obj == null) (
pstmt.setObject (index, "");
) Else (
/ / Else set object
pstmt.setObject (index, obj);
)

/ / next index
index + +;
)
)
) Catch (SQLException ex) (
throw new DaoException ( "can not apply parameter", ex);
)
)

Then we went on to say that our method of inquiry, despite the above two methods, our method of query is very simple:
public List query (String sql, List params) throws DaoException (
List result = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
try (
pstmt = conn.prepareStatement (sql);
this.apply (pstmt, params);
rs = pstmt.executeQuery ();
result = this.convert (rs);
) Catch (SQLException ex) (
throw new DaoException ( "can not execute query", ex);
) Finally (
if (rs! = null) (
try (
rs.close ();
) Catch (SQLException e) (
/ / Nothing
)
)
if (pstmt! = null) (
try (
pstmt.close ();
) Catch (SQLException e) (
/ / Nothing
)
)
)

return result;
)

Special query methods (single return value)
Sometimes, for ease of use, we need to return a single value search method of production, such as select max (id) from table_a, select count (id) from table_b and so on. The following code uses the above-mentioned common query method, the code is:
public Object queryOne (String sql, List params) throws DaoException (
List list = this.query (sql, params);

if (list == null | | list.size () == 0) (
throw new DaoException ( "data not exist");
) Else (
Map record = (Map) list.get (0);
if (record == null | | record.size () == 0) (
throw new DaoException ( "data not exist");
) Else (
return record.values (). toArray () [0];
)
)
)

Update, delete, insert JDBC Ways at because of these three methods are execute with a finish, so here we also use a way to achieve these functions. Code as follows:
public int execute (String sql, List params) throws DaoException (
int ret = 0;
PreparedStatement pstmt = null;
try (
pstmt = conn.prepareStatement (sql);
this.apply (pstmt, params);
ret = pstmt.executeUpdate ();
) catch (SQLException ex) (
throw new DaoException ( "", ex);
) Finally (
if (pstmt! = null) (
try (
pstmt.close ();
) Catch (SQLException e) (
/ / Nothing.
)
)
)

return ret;
)

Batch methods (inquiries)
Sometimes in order to facilitate the operation, required more than one SQL query statement, we call the batch, see the following implementation methods, and query methods in order to make the distinction between the parameters and return values are replaced by an array of forms.

public List [] queryBatch (String [] sqlArray, List [] paramArray) throws DaoException (
List rets = new ArrayList ();
if (sqlArray.length! = paramArray.length) (
throw new DaoException ( "sql size not equal parameter size");
) Else (
for (int i = 0; i <sqlArray.length; i + +) (
String sql = sqlArray [i];
List param = paramArray [i];
List ret = this.query (sql, param);
rets.add (ret);
)
return (List []) rets.toArray ();
)
)

Batch method (update)
Sometimes be necessary to update many Sql statement, in order to facilitate the operation, added a batch update operation, see the following code, and update methods in order to distinguish between the parameters and return values are replaced by an array of forms.
public int [] executeBatch (String [] sqlArray, List [] paramArray) throws DaoException (
List rets = new ArrayList ();
if (sqlArray.length! = paramArray.length) (
throw new DaoException ( "sql size not equal parameter size");
) Else (
for (int i = 0; i <sqlArray.length; i + +) (
int ret = this.execute (sqlArray [i], paramArray [i]);
rets.add (new Integer (ret));
)

int [] retArray = new int [rets.size ()];
for (int i = 0; i <retArray.length; i + +) (
retArray [i] = ((Integer) rets.get (i)). intValue ();
)

return retArray;
)
)

Release resources CommonDao because there is a property of the Connection and Connection belong to the scarcity of resources, so do not need to use CommonDao at the time required to display closed Connection. Code is as follows:
public void close () throws DaoException (
try (
if (conn! = null & & conn.getAutoCommit ()) (
conn.close ();
) Else (
if (conn == null) (
throw new DaoException ( "can not close null connection, first new then close");
) Else (
throw new DaoException ( "transaction is running, rollbakc or commit befor close please.");
)
)
) Catch (SQLException ex) (
throw new DaoException ( "Can not close common dao");
)
)

JDBC type of instrument (JDBCUtil Class)
The code in the above we can see that there is a lot of useless treatment, such as:
if (pstmt! = null) (
try (
pstmt.close ();
) Catch (SQLException e) (
/ / Nothing.
)
)
Why do we need these to deal with that? Say the first such deal happened in the normal position after the completion of treatment, the treatment (such as pstmt.close ()) would not be affected even if the failure, this time we need to do the deal useless, this is a small JDBC API small flaw. We usually use a special tool to do static added, such as:

package com.jpleasure.jdbc.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class JDBCUtil (
public void safelyClose (Connection conn) (
if (conn! = null) (
try (
conn.close ();
) Catch (SQLException e) (
/ /
)
)
)
public void safelyClose (PreparedStatement pstmt) (
if (pstmt! = null) (
try (
pstmt.close ();
) Catch (SQLException e) (
/ /
)
)
)
public void safelyClose (ResultSet rs) (
if (rs! = null) (
try (
rs.close ();
) Catch (SQLException e) (
/ /
)
)
)
)

Exception handling may be careful you have found a problem, why is all out of place we are all abnormal SQLException packaging will be at the DaoException out of it, why do not directly SQLException thrown out? There are two reasons, first, can be refined classification abnormal Exception thrown right, add the appropriate message, and secondly, to isolate and Dao and the coupling of business logic can be easily modified without affecting the Dao layer to business logic layer. Also to note, DaoExcetion can contain SQLException, this time for the customer to provide more detailed error information, such as ORA-12524, etc., but rarely seen.

package com.jpleasure.jdbc.dao;

public class DaoException extends Exception (

public DaoException () (
super ();
)

public DaoException (String message, Throwable cause) (
super (message, cause);
)

public DaoException (String message) (
super (message);
)

public DaoException (Throwable cause) (
super (cause);
)

)

Original Address: http://www.blogjava.net/super2/archive/2008/11/01/237987.html