平时我们使用jdbc的时候经常需要把resultset-->List,以被其他层调用,其实我们使用o/r开源工具Torque,hibernate就有类似包装好的,非常好用.
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method; //返回方法
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.List;
import org.apache.log4j.Logger;
import com.scitel.crms.business.dao.*;
/**
*
* <p>Title:运用类反射机制来实现 </p>
* <p>Description:持久化层DAO层简化:通用查询类 </p>
*/
public class QueryUtil extends BasicDAO {
private static Logger log = Log.getLog(QueryUtil.class);
private Connection con = null;
private PreparedStatement pstmt = null;
private ResultSet rs = null;
/**
* 完成ResultSet对象向List对象为集合的对象的转化
* @param sql,指定的查询Sql
* @param className,Sql相对应的JavaBean/FormBean类的名字:具体的Vo值对象或ActionForm
* @Return:以类className为一条记录的结果集,
* 完成ResultSet对象向List对象为集合的className对象的转化
*/
public List Select(String sql, String className) {
List arr = null; //数组来处理
try {
con = DBTool.getDAOConnection(); //取得数据库连接
pstmt = con.prepareStatement(sql);
rs = pstmt.executeQuery(); //执行查询
String recordValue = ""; //构造返回的结果集
Object c1 = null;
arr = new ArrayList();
ResultSetMetaData rsmd = rs.getMetaData(); //取得数据表中的字段数目,类型等返回结果
//是以ResultSetMetaData对象保存
int columnCount = rsmd.getColumnCount(); //列的总数
while (rs.next()) {
c1 = Class.forName(className).newInstance(); //类的实例化
for (int i = 1; i <= columnCount; i++) {
if (rs.getString(rsmd.getColumnName(i)) != null) {
recordValue = rs.getString(rsmd.getColumnName(i));
} else {
recordValue = "";
}
Method
m = c1.getClass().getMethod(getSetMethodName(rsmd.getColumnName(i)),
new Class[] {recordValue.getClass()});
m.invoke(c1, new Object[] {recordValue});
}
log.info("取得ActionForm或VO中的set方法" +
getSetMethodName(rsmd.getColumnName(1)));
arr.add(c1);
}
} catch (SQLException ex) {
} catch (ClassNotFoundException e) {
} catch (NoSuchMethodException e) {
} catch (InvocationTargetException e) {
} catch (IllegalAccessException e) {
} catch (InstantiationException e) {
} finally {
release(rs, pstmt, con); //释放资源
}
return arr;
}
//在JavaBean封装的商业逻辑中调用Select 方法,然后在JSP页面上显示出来:
//Function:取得用户列表
//Para:
//Return:返回用户列表
public List getUsers(){
List ret=null;
DatabaseManage db=new DatabaseManage();
String sql=" select usr_id,usr_name "
+" from users " ;
ret=db.Select(sql," com.mcsky. webis.system.UsersActionForm");
return ret;
}
public static void main(String[] args) {
//方法测试通过
String sql =
"select chkr_code,chkr_name,chkr_value chkr_regular from checkrule "; //查询告警用户过滤设置明细
QueryUtil util = new QueryUtil();
List arr = null;
arr = util.Select(sql, "com.scitel.crms.web.form.TestActionForm");
System.out.println("集合大小------>>>>>>>" + arr.size());
//System.out.println("集合大小------>>>>>>>"+arr.toArray().toString());
}
}