Java+Swing: 从数据库中查询数据并显示在表格中 整理11

分析:要想从数据库中查询数据并分页展示到表格中,我觉得应该按照这个思路:首先就是发起请求,此时需要向数据库中传递三个参数:当前页码(pageNum)每一页的数量(pageSize)搜索的关键词(searchKey)控制从第几页开始(startPageNum)

然后就是接受返回的结果数据(data)总数据条数(totalCount)

1. 首先在MainView中定义两个变量,给出初始值

java 复制代码
    // 分页:定义两个变量
    private int pageNum = 1;  // 当前是第几页
    private int pageSize = 10; // 一页显示多少条数据

2. 创建请求的类对象

java 复制代码
package com.resquest;

import lombok.Data;

/**
 * @Author:xiexu
 * @Date:2023/12/12 12:59
 */
@Data
public class StudentRequest {
    private int pageNum;
    private int pageSize;
    private String searchKey;   //  搜索关键字

    private int startPageNum;  // 控制从第几页开始

    public int getStartPageNum() {
        return (pageNum - 1) * pageSize;
    }
    public void setStartPageNum(int startPageNum) {
        this.startPageNum = startPageNum;
    }
}

3. 创建接受返回结果的类对象

java 复制代码
package com.response;

import lombok.Data;

import java.util.Vector;

/**
 * @Author:xiexu
 * @Date:2023/12/12 13:07
 */
@Data
public class TableDTO {
    private Vector<Vector<Object>> data;
    private int totalCount;
}

4. 定义接口

返回的结果是TableDTO类型

java 复制代码
public interface StudentService {
    TableDTO queryStudent(StudentRequest studentRequest);
}

5. 实现接口

java 复制代码
package com.service.Impl;

import com.response.TableDTO;
import com.resquest.StudentRequest;
import com.service.StudentService;
import com.utils.DBUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Vector;

/**
 * @Author:xiexu
 * @Date:2023/12/11 10:40
 */
public class StudentServiceImpl implements StudentService {
    @Override
    public TableDTO queryStudent(StudentRequest studentRequest){
        StringBuilder sql = new StringBuilder();
        sql.append("select * from detail ");

        if (studentRequest.getSearchKey() != null && !"".equals(studentRequest.getSearchKey().trim())) {
            sql.append(" where name like '%"+ studentRequest.getSearchKey() + "%'");
        }

        sql.append("order by id desc limit ").append(studentRequest.getStartPageNum())
                .append(",").append(studentRequest.getPageSize());

        // 执行
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;
        TableDTO tableDTO = new TableDTO(); // 返回的数据
        try {
            connection = DBUtil.getConnection();
            preparedStatement = connection.prepareStatement(sql.toString());
            resultSet = preparedStatement.executeQuery();  // 执行查询返回结果集

            // 查询记录
            Vector<Vector<Object>> queryDatas = fillTableData(resultSet);
            tableDTO.setData(queryDatas);

            sql.setLength(0);
            sql.append("select count(*) from detail ");

            if (studentRequest.getSearchKey() != null && !"".equals(studentRequest.getSearchKey().trim())) {
                sql.append(" where name like '%"+ studentRequest.getSearchKey() + "%'");
            }

            preparedStatement = connection.prepareStatement(sql.toString());
            resultSet = preparedStatement.executeQuery();
            while (resultSet.next()) {
                int count = resultSet.getInt(1);
                tableDTO.setTotalCount(count);
            }
            return tableDTO;

        }catch (Exception e) {
            e.printStackTrace();
        } finally {
            DBUtil.closeRS(resultSet);
            DBUtil.closePS(preparedStatement);
            DBUtil.closeConnection(connection);
        }

        return null;
    }

    private static Vector<Vector<Object>> fillTableData(ResultSet resultSet) throws SQLException {
        Vector<Vector<Object>> data = new Vector<>();
        while (resultSet.next()) {
            // 遍历查询的每一条记录
            Vector<Object> oneRecord = new Vector<>();
            int id = resultSet.getInt("id");
            String name = resultSet.getString("name");
            String no = resultSet.getString("no");
            String homeTown = resultSet.getString("homeTown");
            int chinese = resultSet.getInt("chinese");
            int math = resultSet.getInt("math");
            int english = resultSet.getInt("english");
            int total = resultSet.getInt("total");

            oneRecord.addElement(id);
            oneRecord.addElement(name);
            oneRecord.addElement(no);
            oneRecord.addElement(homeTown);
            oneRecord.addElement(chinese);
            oneRecord.addElement(math);
            oneRecord.addElement(english);
            oneRecord.addElement(total);

            data.addElement(oneRecord);
        }

        return data;
    }
}

上述代码详细解释:

  1. 下方代码主要是编写sql语句的, 使用StringBuilder()动态构建字符串。 首先判断searchKey是否为空或是否为空字符串,false的话,就直接下方的sql语句,如果为true的话,需要按照name进行模糊查询,然后再拼接下方的sql语句
java 复制代码
        StringBuilder sql = new StringBuilder();
        sql.append("select * from detail ");

        if (studentRequest.getSearchKey() != null && !"".equals(studentRequest.getSearchKey().trim())) {
            sql.append(" where name like '%"+ studentRequest.getSearchKey() + "%'");
        }

        sql.append("order by id desc limit ").append(studentRequest.getStartPageNum())
                .append(",").append(studentRequest.getPageSize());
  1. 查询数据,并注入到tableDTO中
java 复制代码
// 查询记录
 Vector<Vector<Object>> queryDatas = fillTableData(resultSet);
 tableDTO.setData(queryDatas);

fillTableData函数:

java 复制代码
private static Vector<Vector<Object>> fillTableData(ResultSet resultSet) throws SQLException {
        Vector<Vector<Object>> data = new Vector<>();
        while (resultSet.next()) {
            // 遍历查询的每一条记录
            Vector<Object> oneRecord = new Vector<>();
            int id = resultSet.getInt("id");
            String name = resultSet.getString("name");
            String no = resultSet.getString("no");
            String homeTown = resultSet.getString("homeTown");
            int chinese = resultSet.getInt("chinese");
            int math = resultSet.getInt("math");
            int english = resultSet.getInt("english");
            int total = resultSet.getInt("total");

            oneRecord.addElement(id);
            oneRecord.addElement(name);
            oneRecord.addElement(no);
            oneRecord.addElement(homeTown);
            oneRecord.addElement(chinese);
            oneRecord.addElement(math);
            oneRecord.addElement(english);
            oneRecord.addElement(total);

            data.addElement(oneRecord);
        }

        return data;
    }
  1. 查询数据数量
java 复制代码
            sql.setLength(0);  // 首先将之前的sql语句置为空
            sql.append("select count(*) from detail ");

            if (studentRequest.getSearchKey() != null && !"".equals(studentRequest.getSearchKey().trim())) {
                sql.append(" where name like '%"+ studentRequest.getSearchKey() + "%'");
            }

            preparedStatement = connection.prepareStatement(sql.toString());
            resultSet = preparedStatement.executeQuery();
            while (resultSet.next()) {
                int count = resultSet.getInt(1);
                tableDTO.setTotalCount(count);
            }
  1. MainView中使用
java 复制代码
        StudentServiceImpl studentService = new StudentServiceImpl();
        StudentRequest studentRequest = new StudentRequest();
        studentRequest.setPageNum(pageNum);
        studentRequest.setPageSize(pageSize);
        studentRequest.setSearchKey(searchTxt.getText().trim());

        TableDTO tableDTO = studentService.queryStudent(studentRequest);
        Vector<Vector<Object>> data = tableDTO.getData();
        int totalCount = tableDTO.getTotalCount();

5.运行结果

本篇博客中涉及的数据库连接的相关代码请参考:http://t.csdnimg.cn/eYNmw

相关推荐
大数据编程之光9 分钟前
Flink Standalone集群模式安装部署全攻略
java·大数据·开发语言·面试·flink
爪哇学长23 分钟前
双指针算法详解:原理、应用场景及代码示例
java·数据结构·算法
ExiFengs26 分钟前
实际项目Java1.8流处理, Optional常见用法
java·开发语言·spring
paj12345678928 分钟前
JDK1.8新增特性
java·开发语言
繁依Fanyi39 分钟前
简易安卓句分器实现
java·服务器·开发语言·算法·eclipse
慧都小妮子1 小时前
Spire.PDF for .NET【页面设置】演示:打开 PDF 时自动显示书签或缩略图
java·pdf·.net
m51271 小时前
LinuxC语言
java·服务器·前端
IU宝1 小时前
C/C++内存管理
java·c语言·c++
瓜牛_gn1 小时前
依赖注入注解
java·后端·spring
hakesashou1 小时前
Python中常用的函数介绍
java·网络·python