Java 分页
                
                
                
                    
                        - 摘要:publicListgetListPage(Classc,Stringsql,LongpageIndex,intpageRecordCount,Object[]paramsValue){Listlist=newArrayList();//创建集合com.dwp.util.DataSourceds=newcom.dwp.util.DataSource();//创建数据源Connectionconn=ds.getConnection()
- 标签:Java 
 
                
                    
                    
    public List getListPage(Class c, String sql, Long pageIndex,
			int pageRecordCount, Object[] paramsValue) {
		List list = new ArrayList(); // 创建 集合
		com.dwp.util.DataSource ds = new com.dwp.util.DataSource(); // 创建 数据源
		Connection conn = ds.getConnection(); // 获得数据库联接
		PreparedStatement pstmt = null; // 声明 sql语句执行器
		ResultSet rs = null; // 声明 结果集
		try {
			conn.setAutoCommit(false);
			String queryStr = "";
			if (pageIndex > 0) {
				// 创建 sql语句(带分页)
				queryStr = "select * from (select temp.*, rownum rownum_ from ("
						+ sql + ")temp where rownum <= ?) where rownum_ >?";
			} else {
				queryStr = sql;
			}
			pstmt = conn.prepareStatement(queryStr);
			// sql语句 参数索引 (无条件分页时)
			int paramIndex = 1;
			if (null != paramsValue) {
				for (int i = 0; i < paramsValue.length; i++) {
					pstmt.setObject(i + 1, paramsValue[i]);
				}
				paramIndex = paramsValue.length + 1;
			}
			if (pageIndex > 0) {// 如果指定的分页
				// 给分页 参数赋值
				pstmt.setLong(paramIndex, pageIndex * pageRecordCount);
				pstmt.setLong(paramIndex + 1, (pageIndex - 1)
								* pageRecordCount);
			}
			rs = pstmt.executeQuery();
			conn.commit();// 提交事务
			Field[] fields = c.getDeclaredFields();
			String fieldName = null;
			String fieldType = null;
			while (rs.next()) {
				try {
					Object o = c.newInstance();
					for (Field field : fields) {
						fieldName = field.getName();
						fieldType = field.getType().getSimpleName();
						Method method = c.getDeclaredMethod("set"
								+ fieldName.substring(0, 1).toUpperCase()
								+ fieldName.substring(1), field.getType());
						if ("String".equals(fieldType)) {
							method.invoke(o, rs.getString(fieldName));
						} else if ("Date".equals(fieldType)) {
							method.invoke(o, rs.getDate(fieldName));
						} else if ("int".equals(fieldType)) {
							method.invoke(o, rs.getInt(fieldName));
						} else if ("double".equals(fieldType)) {
							method.invoke(o,rs.getDouble(fieldName));
						}
					}
					list.add(o);
				} catch (InstantiationException e) {
					e.printStackTrace();
				} catch (IllegalAccessException e) {
					e.printStackTrace();
				} catch (SecurityException e) {
					e.printStackTrace();
				} catch (NoSuchMethodException e) {
					e.printStackTrace();
				} catch (IllegalArgumentException e) {
					e.printStackTrace();
				} catch (InvocationTargetException e) {
					e.printStackTrace();
				}
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			ds.close(conn, pstmt, rs);
		}
		return list;
	}