日期:2014-05-16 浏览次数:20550 次
public static List queryList(String preSql, String className, Connection con, int offset, int pagelength) throws PortalException { List beanbasket = new ArrayList(); String[] columns = null; if (con == null) { con = getConnection(); } //查询出的结果集 ResultSet rs = null; PreparedStatement pstmt = null; try { pstmt = con.prepareStatement(preSql); if (pagelength != 0) { int endnum = offset+pagelength; int stratnum = offset+1; pstmt.setInt(1, endnum); pstmt.setInt(2, stratnum); } LogFactory.debug("will query the data!!"); rs = pstmt.executeQuery(); LogFactory.debug("query the data success!!!"); ResultSetMetaData metedata = rs.getMetaData(); //获取查询出的字段总数 int i = metedata.getColumnCount(); //获取数据库表中所有的字段名 columns = new String[i]; for (int j = 1; j < i+1; j++) { columns[j-1] = metedata.getColumnName(j); } Class clazz = Class.forName(className); Field[] fields = clazz.getDeclaredFields(); LogFactory.debug("the fields length is:" + fields.length); while (rs.next()) { Object obj = clazz.newInstance(); for (Field f : fields) { //如果该字段在数据库中有存储 if(isContainField(f.getName(),columns)){ f.setAccessible(true); String strType = f.getType().toString(); if (strType.indexOf("Long") != -1) { f.set(obj, rs.getLong(f.getName())); } else if (strType.indexOf("Integer") != -1 || strType.indexOf("int") != -1) { f.set(obj, rs.getInt(f.getName())); } else if (strType.indexOf("String") != -1) { String s = rs.getString(f.getName()); if(s!=null&&!s.equals("null")) { s =s.trim(); } else { s = ""; } f.set(obj, s); } else if (strType.indexOf("Date") != -1) { f.set(obj, rs.getDate(f.getName())); } else if (strType.indexOf("Double") != -1) { f.set(obj, rs.getDouble(f.getName())); } else if (strType.indexOf("Float") != -1) { f.set(obj, rs.getFloat(f.getName())); } else { LogFactory.debug( "this data type not support yet!"); LogFactory.debug("this date type is" + f.getName()); } } beanbasket.add(obj); } } catch (Exception ex) { } LogFactory.info("Exit DBProxy.querylist()"); return beanbasket; }