First of all thanks to Wolf Brother Lonely Wolf blog, the entire JDBC Learning blog data link for http://www.cnblogs.com/xdp-gacl/p/4006830.html
Detailed code see Wolf Brother blog, List of my learning process encountered problems it.
public static Object query(String sql, Object[] params, ResultSetHandler rsh) throws SQLException { Connection conn = null; PreparedStatement ppst = null; ResultSet rs = null; try { conn = getConnection(); ppst = conn.prepareStatement(sql); for (int i = 0; i < params.length; i++) { ppst.setObject(i + 1, params[i]); } rs = ppst.executeQuery(); return rsh.handler(rs);//关于这个策略模式的学习,详见设计模式吧,熟悉这种写法,在公司的工作过程中,类似写法遇到过,有用! } finally { release(conn, ppst, rs); } }
The following call
public User queryByID(int id) throws SQLException{ String sql = "select * from user where uid=?"; return (User) JDBCUtil.query(sql,new Object[]{id}, new BeanHandler(User.class)); }
Then Beanhandler is actually the implementation class of Resultsethandler excuses, the main purpose is to put the results of the query into the JavaBean obtained through the launch, but also from the database loaded into the JVM memory
Package Dbex.domain;import Java.lang.reflect.field;import Java.sql.resultset;import java.sql.ResultSetMetaData; Import Java.sql.sqlexception;public class Beanhandler implements Resultsethandler {private class<?> clazz; Public Beanhandler (class<?> clazz) {this.clazz = Clazz; } public Object Handler (ResultSet rs) {object bean=null; try {if (!rs.next ()) {//NULL returns the null return bean directly; }//Put the column data in the ResultSet object into the bean corresponding attribute to the Bean = Clazz.newinstance (); ResultSetMetaData rsm = Rs.getmetadata (); int len = Rsm.getcolumncount (); for (int i = 0; i < len; i++) {String name = Rsm.getcolumnname (i + 1); Object data = Rs.getobject (i+1); Field field = Clazz.getdeclaredfield (name); Field.setaccessible (TRUE); String type = Rsm.getcolumntypename (i+1);//if ("INTEGER". Equals (Type)) {// System.out.println (type); Field.set (Bean,data.tostring ());//}else if ("String". Equalsignorecase (Type)) {//Field.set (BE An, (String) data);//System.out.println (type);//}else{//Field.set (Bean, DA TA);//}}} catch (Exception e) {e.printstacktrace (); } return bean; }}
Summary: policy mode ,java reflection
JDBC Learning Review 10 Writing your own JDBC framework