分页查询信息

使用jdbc连接mysql数据库实现分页查询任务

通过mysql数据库提供的分页机制,实现商品信息的分页查询功能,将查询到的信息显示到jsp页面上。

本项目时一个简单的运用eclipse+jdbc+mysql的小程序。

连接的数据库名称为db_database11,属性如下: 

创建名为com.pmf.bean的包,包中是名为Product的类,用于封装商品信息。

全部代码如下:

package com.pmf.bean;
 
/**
品
 *
 */
public class Product {
public static final int PAGE_SIZE = 2;
// 编号
private int id;
// 名称
private String name;
// 价格
private double price;
// 数量
private int num;
// 单位
private String unit;
 
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public int getNum() {
return num;
}
public void setNum(int num) {
this.num = num;
}
public String getUnit() {
return unit;
}
public void setUnit(String unit) {
this.unit = unit;
}
}

2.创建名为“BookDao”的类,主要用于封装商品数据库的相关操作。在BookDao类中首先编写getConnection()方法,用于创建Connection对象。接着创建商品信息的分页查询方法find(),其中page参数用于传递要查询的页码。在分页查询过程中还需要获取信息的总记录数,用于计算商品信息的总页数。此方法写在findCount()方法中。

代码如下:

package com.pmf.bean;
 
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
 
/**
 * 商品数据库操作
 *
 */
 
public class BookDao {
/**
 * 获取数据库连接
 * @return Connection对象
 */
public Connection getConnection(){
// 数据库连接
Connection conn = null;
try {
// 加载数据库驱动,注册到驱动管理器
Class.forName("com.mysql.jdbc.Driver");
// 数据库连接字符串
String url = "jdbc:mysql://localhost:3306/db_database11";
// 数据库用户名
String username = "root";
// 数据库密码
String password = "123123";
// 创建Connection连接
conn = DriverManager.getConnection(url,username,password);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
// 返回数据库连接
return conn;
}
 
/**
 * 分页查询所有商品信息
 * @param page 页数
 * @return List<Product>
 */
public List<Product> find(int page){
// 创建List
List<Product> list = new ArrayList<Product>();
// 获取数据库连接
Connection conn = getConnection();
// 分页查询的SQL语句
String sql = "select * from tb_product order by id desc limit ?,?";
try {
// 获取PreparedStatement
PreparedStatement ps = conn.prepareStatement(sql);
// 对SQL语句中的第1个参数赋值
ps.setInt(1, (page - 1) * Product.PAGE_SIZE);
// 对SQL语句中的第2个参数赋值
ps.setInt(2, Product.PAGE_SIZE);
// 执行查询操作
ResultSet rs = ps.executeQuery();
// 光标向后移动,并判断是否有效
while(rs.next()){
// 实例化Product
Product p = new Product();
// 对id属性赋值
p.setId(rs.getInt("id"));
// 对name属性赋值
p.setName(rs.getString("name"));
// 对num属性赋值
p.setNum(rs.getInt("num"));
// 对price属性赋值
p.setPrice(rs.getDouble("price"));
// 对unit属性赋值
p.setUnit(rs.getString("unit"));
// 将Product添加到List集合中
list.add(p);
}
// 关闭ResultSet
rs.close();
// 关闭PreparedStatement
ps.close();
// 关闭Connection
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
return list;
}
 
/**
 * 查询总记录数
 * @return 总记录数
 */
public int findCount(){
// 总记录数
int count = 0;
// 获取数据库连接
Connection conn = getConnection();
// 查询总记录数SQL语句
String sql = "select count(*) from tb_product";
try {
// 创建Statement
Statement stmt = conn.createStatement();
// 查询并获取ResultSet
ResultSet rs = stmt.executeQuery(sql);
// 光标向后移动,并判断是否有效
if(rs.next()){
// 对总记录数赋值
count = rs.getInt(1);
}
// 关闭ResultSet
rs.close();
// 关闭Connection
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
// 返回总记录数
return count;
}
}
3.创建一个名为“FindServlet”的类位于com.pmf.servlet中。此类是分页查询商品信息的Servlet对象。在该类中写doGet()方法处理分页请求。
代码如下:
package com.pmf.servlet;
 
import java.io.IOException;
import java.util.List;
 
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
import com.pmf.bean.Product;
import com.pmf.bean.BookDao;
 
/**
Servlet
 */
public class FindServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
 
 
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 当前页码
int currPage = 1;
// 判断传递页码是否有效
if(request.getParameter("page") != null){
// 对当前页码赋值
currPage = Integer.parseInt(request.getParameter("page"));
}
// 实例化ProductDao
BookDao dao = new BookDao();
// 查询所有商品信息
List<Product> list = dao.find(currPage);
// 将list放置到request之中
request.setAttribute("list", list);
// 总页数
int pages ;
// 查询总记录数
int count = dao.findCount();
// 计算总页数
if(count % Product.PAGE_SIZE == 0){
// 对总页数赋值
pages = count / Product.PAGE_SIZE;
}else{
// 对总页数赋值
pages = count / Product.PAGE_SIZE + 1;
}
// 实例化StringBuffer
StringBuffer sb = new StringBuffer();
// 通过循环构建分页条
for(int i=1; i <= pages; i++){
// 判断是否为当前页
if(i == currPage){
// 构建分页条
sb.append("『" + i + "』");
}else{
// 构建分页条
sb.append("<a href='FindServlet?page=" + i + "'>" + i + "</a>");
}
// 构建分页条
sb.append(" ");
}
// 将分页条的字符串放置到request之中
request.setAttribute("bar", sb.toString());
// 转发到product_list.jsp页面
request.getRequestDispatcher("product_list.jsp").forward(request, response);
}
 
}
4.创建product_list.jsp页面,此页面通过获取查询结果List与分页条来分页显示商品的数据。
代码如下:
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
 
<%@page import="java.util.List"%>
<%@page import="com.pmf.bean.Product"%><html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>所有商品信息</title>
<style type="text/css">
td{font-size: 12px;}
h2{margin: 0px}
</style>
</head>
<body>
<table align="center" width="450" border="1" height="180" bordercolor="white" bgcolor="black" cellpadding="1" cellspacing="1">
<tr bgcolor="white">
<td align="center" colspan="5">
<h2>所有商品信息</h2>
</td>
</tr>
<tr align="center" bgcolor="#e1ffc1" >
<td><b>ID</b></td>
<td><b>商品名称</b></td>
<td><b>价格</b></td>
<td><b>数量</b></td>
<td><b>单位</b></td>
</tr>
<%
List<Product> list = (List<Product>)request.getAttribute("list");
for(Product p : list){
%>
<tr align="center" bgcolor="white">
<td><%=p.getId()%></td>
<td><%=p.getName()%></td>
<td><%=p.getPrice()%></td>
<td><%=p.getNum()%></td>
<td><%=p.getUnit()%></td>
</tr>
<%
}
%>
<tr>
<td align="center" colspan="5" bgcolor="white">
<%=request.getAttribute("bar")%>
</td>
</tr>
</table>
</body>
</html>
 
5.编写程序中的主页index.jsp,在其中编写分页查询商品信息的超链接指向FindServlet.
代码如下:
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
    <a href="FindServlet">查看所有商品信息</a>
</body>
</html>