新手怎么以最简单的方式实现jsp+mysql分页
2018-04-09
刚开始弄 ,目前分页是在前台jsp中实现的 与bean相比 这样比较容易一些
先把代码贴出来 正在研究怎么样用bean实现分页 等弄好了 再贴代码
下面说下分页理论 select * from message order by time desc limit begin,size
begin 数据记录从第几条开始 begin=(当前页数-1)*size
size 每页的记录数
下面是连接数据库的javabean;
1: package bean;
2: import java.sql.*;
3:
4: public class MyDb{
5: private Statement stmt;
6: private Connection conn=null;
7: private ResultSet rs=null;
8:
9: public void connection(String db_name,String user,String pwd) throws Exception{
10: Class.forName("com.mysql.jdbc.Driver");
11: String url="jdbc:mysql://localhost:3306/" + db_name;
12: conn=DriverManager.getConnection(url,user,pwd);
13: stmt=conn.createStatement();
14: }
15:
16: public ResultSet query(String sql) throws Exception{
17: rs=stmt.executeQuery(sql);
18: return rs;
19: }
20:
21: public ResultSet query(String sql,int begin,int size) throws Exception{
22: String s=" limit " + begin + "," +size;
23: sql=sql + s;
24: rs=stmt.executeQuery(sql);
25: return rs;
26: }
27:
28:
29: public int update(String sql) throws Exception{
30: int n=0;
31: n=stmt.executeUpdate(sql);
32: return n;
33: }
34:
35: public boolean delete(String sql) throws Exception{
36: 0ff">boolean flag=false;
37: flag=stmt.execute(sql);
38: return flag;
39: }
40: }
下面是jsp的代码;
1: <jsp:useBean id="db" class="bean.MyDb" scope="page" />
2: <%
3: int page_count; //总页数
4: int p; //当前面号
5: int size=3; //每页记录数
6: int result_count; //总记录数
7: int begin; //当前页第一条记录索引号
8: ResultSet rs=null;
9: String page_s=request.getParameter("page");
10: if(page_s==null) page_s="1";
11: db.connection("test","root","root");
12: String sql="select count(*) from message";
13: rs=db.query(sql);
14: rs.next();
15: result_count=rs.getInt(1);
16: page_count=(result_count + size - 1)/size;
17: p=Integer.parseInt(page_s);
18: out.println("总记录数为:" + result_count + " 每页记录数为:" + size + " 总页数为:" + page_count + " 当前是第" + p + "页");
19: sql="select * from message order by time desc";
20: begin=(p-1)*size;
21: rs=db.query(sql,begin,size);
22: while(rs.next()){
23: %>
24: <table>
25: <tr>
26: <td width="200"><%=rs.getString(1)%></td>
27: <td width="200"><%=rs.getString(2)%></td>
28: </tr>
29: <tr>
30: <td><%=rs.getString(3)%></td>
31: <td><%=rs.getString(4)%></td>
32: </tr>
33: <tr><td colspan="2"><%=rs.getString(5)%></td></tr>
34: <tr><td colspan="2"><hr /></td></tr>
35: </table>
36: <%
37: }
38: if(p>1) out.println("<a href=test.jsp?page=" + (p-1) + ">上一页</a>");
39: if(p<page_count) out.println("<a href=test.jsp?page=" + (p+1) + ">下一页</a>");
40: %>
广告 您可能关注的内容 |