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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值