---
title: "jdbc分页"
author: "diaochenlong2"
date: "2014-02-18T21:03:12Z"
tags: ["mysql分页"]
categories: ["编程语言"]
slug: "jdbc"
draft: false
lastmod: "2014-02-18T22:12:30Z"
id: 2018883
url: "https://diaochenlong2.iteye.com/blog/2018883"
---

\[code="java"] &lt;%@ page contentType="text/html; charset=gb2312" %&gt; &lt;%@ page language="java" %&gt; &lt;%@ page import="java.sql.\*" %&gt; 分页显示数据库记录

**分页显示数据库记录**

* * *

&lt;% try { String driverName="com.mysql.jdbc.Driver"; //驱动程序名 String userName="root";//数据库用户名 String userPasswd="longchendiao";//密码 String dbName="book";//数据库名 //连接字符串 String url="jdbc:mysql://localhost:3306/"+dbName+"?user="+userName+"&password="+userPasswd+"&useUnicode=true&characterEncoding=GB2312"; Class.forName(driverName).newInstance();//加载驱动程序 Connection conn=DriverManager.getConnection(url); String sql="select * from bookInfo";//创建执行语句 Statement stmt=conn.createStatement(); ResultSet rs=stmt.executeQuery(sql); int intPageSize; //一页显示的记录数 int intRowCount; //记录的总数 int intPageCount; //总页数 int intPage; //待显示的页码 当前页码 String strPage; int i; intPageSize = 3; //设置一页显示的记录数 strPage = request.getParameter("page");//取得待显示的页码 if(strPage == null) //判断strPage是否等于null,如果是，显示第一页数据 { intPage = 1; }else{ intPage=java.lang.Integer.parseInt(strPage); //将字符串转换为整型 } if(intPage &lt; 1) { intPage=1; } rs.last();//获取记录总数 intRowCount = rs.getRow(); intPageCount = (intRowCount%intPageSize)==0?(intRowCount/intPageSize):(intRowCount/intPageSize + 1); //计算机总页数 if(intPage &gt; intPageCount) intPage = intPageCount; //调整待显示的页码 if(intPageCount&gt;0) { rs.absolute((intPage-1)\*intPageSize+1); //将记录指针定位到待显示页的第一条记录上 } //下面用于显示数据 i=0; while(i &lt;% rs.next(); i++; } rs.close();//关闭连接、释放资源 stmt.close(); conn.close(); %&gt;

图书名称 出版社 图书价格 &lt;%=rs.getString(2)%&gt; &lt;%=rs.getString(3)%&gt; &lt;%=rs.getString(4)%&gt;

共&lt;%=intRowCount%&gt;个记录，分&lt;%=intPageCount%&gt;页显示，当前页是：第&lt;%=intPage%&gt;页 &lt;% for(int j=1;j&lt;=intPageCount;j++) { out.print("  ["+j+"](MySQLFen.jsp?page=%22%20j%20%22)"); } %&gt;

&lt;% } catch(Exception e) { e.printStackTrace(); } %&gt;

IT在中国电脑学习网！@2007  
公司地址:郑州市二七路200号金博大D座2708室  
电话:66202195 电子邮件:[](mailto:liuhaisong9462@sohu.com) itzcn@126.com

\[/code]