分頁查詢信息(使用jdbc連接mysql數據庫實現分頁查詢任務)


         分頁查詢信息

      使用jdbc連接mysql數據庫實現分頁查詢任務

通過mysql數據庫提供的分頁機制,實現商品信息的分頁查詢功能,將查詢到的信息顯示到jsp頁面上。

本項目時一個簡單的運用eclipse+jdbc+mysql的小程序。

連接的數據庫名稱為db_database11屬性如下:

 

 1.創建名為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 implementation class FindServlet

 */

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>

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM