JSP读取MySql数据库实现分页效果
下面是用MV模式做的一个简单的登录后实现分页显示数据信息的页面,后面会用MVC模式改写。
package com.ly.model;
import java.sql.*;
import java.util.ArrayList;
public class UserbeanCl {
private Statement st = null;
private ResultSet rs = null;
private Connection ct = null;
private int pageSize = 10;
private int rowCount = 0;
private int pageCount = 0;
//得到应显示的页码数
public int pageCount() {
try {
// 得到连接
ct = new connDB().getConn();
st=ct.createStatement();
rs = st.executeQuery("select count(*) from students");
//
if(rs.next()){
rowCount=rs.getInt(1);
}
if(rowCount%pageSize==0){
pageCount=rowCount/pageSize;
}else{
pageCount=rowCount/pageSize+1;
}
} catch (Exception e) {
e.printStackTrace();
} finally {
shutup();
}
return pageCount;
}
// 返回分页信息,用ArrayList对象存储
public ArrayList getUsersByPage(int PageNow) {
pageCount = pageCount();
ct = new connDB().getConn();
int startRow=(PageNow-1)*pageSize;
ArrayList al = new ArrayList();
try {
st = ct.createStatement();
rs=st.executeQuery("SELECT * FROM `students` LIMIT "+startRow+","+pageSize);
while(rs.next()){
Userbean ub=new Userbean();
ub.setId(rs.getInt(1));
ub.setName(rs.getString(2));
ub.setGrade(rs.getInt(3));
ub.setBatch(rs.getInt(4));
ub.setPassword(rs.getInt(5));
ub.setGxqm(rs.getString(6));
al.add(ub);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
shutup();
}
return al;
}
//验证用户登录
public boolean checkUser(String u, String p) {
boolean b = false;
ct = new connDB().getConn();
try {
st = ct.createStatement();
ResultSet rs = st
.executeQuery("select password from students where name='"
+ u + "'");
if (rs.next()) {
// 说明用户名存在
if (rs.getString(1).equals(p)) {
// 密码正确
b = true;
} else {
return false;
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
shutup();
}
return b;
}
// 关闭连接释放资源
public void shutup() {
try {
if (rs != null)
rs.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
if (st != null)
st.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
if (ct != null)
ct.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}