qq_57931996 2023-04-01 12:26 采纳率: 88.9%
浏览 32
已结题

JSP链接数据库操作

JSP链接数据库操作
调用DAO中search方法返回结果为空
我觉得应该是dao search方法中的问题但是找不到!烦请指点

img

img

InformationDAO.java


public Map<String, Object> search(PageBean pb, Information information) throws Exception {
        PreparedStatement stmt = null; // 语句对象
        ResultSet rs = null; // 数据集
        List<Information> list = new ArrayList<Information>(); // 公司资讯集合

        // 查询总记录数;设置到pb对象中
        int totalCount = this.getTotalCount();
        pb.setTotalCount(totalCount);

        // 判断(预防当前页为首页或末页时,点击上一页或下一页出错)
        if (pb.getCurrentPage() <= 0) {
            pb.setCurrentPage(1); // 把当前页设置为1
        } else if (pb.getCurrentPage() > pb.getTotalPage()) {
            pb.setCurrentPage(pb.getTotalPage()); // 把当前页设置为最大页数
        }
        // 获取当前页:计算查询的起始行、返回的行数
        int currentPage = pb.getCurrentPage(); // 当前页
        int index = (currentPage - 1) * pb.getPageCount(); // 查询的起始行
        int count = pb.getPageCount(); // 查询返回的行数
        try {
            String sql = "select * from Information where title like concat('%','?','%') limit ?,?;"; // SQL语句
            stmt = DBHelper.getConnection().prepareStatement(sql); // 创建链接对象
            stmt.setString(1, information.getTitle()); //设置SQL语句第一个参数标题的值
            stmt.setInt(2, index);  //设置SQL语句第一个参数初始偏移量
            stmt.setInt(3, count);  //设置SQL语句第二个参数返回记录行最大数目
            rs = stmt.executeQuery(); // 获得数据集
            while (rs.next()) {
                System.out.println("sdfadfsad");
                Information lists = new Information();  //创建一个Information对象
                lists.setId(rs.getInt("id"));        //将公司资讯ID的值加入lists
                lists.setTitle(rs.getString("title"));    //将公司资讯标题的值加入lists
                lists.setAuthor(rs.getString("author"));    //将公司资讯作者的值加入lists
                lists.setContent(rs.getString("content"));    //将公司资讯内容的值加入lists
                lists.setDate(rs.getString("date"));    //将公司资讯发布时间的值加入lists
                list.add(lists); // 把一个公司资讯加入集合
            }
            //创建一个hashMap,key是String类型,value是Object类型(任意类型)
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("PageDate", pb); //将分页对象pb添加到map集合中
            map.put("list", list); //将公司资讯集合对象list添加到map集合中
            return map;    //返回map集合
        } catch (Exception ex) {
            ex.printStackTrace();
            return null;
        } finally {
            // 释放数据集对象
            if (rs != null) {
                try {
                    rs.close();
                    rs = null;
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }
            // 释放语句对象
            if (stmt != null) {
                try {
                    stmt.close();
                    stmt = null;
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }
        }
    }
public int getTotalCount() throws Exception{
        PreparedStatement pStatement = null;
        ResultSet rSet = null;
        String sql = "select count(*) from information;";
        int count = 0;
        try {
            pStatement = DBHelper.getConnection().prepareStatement(sql);
            rSet = pStatement.executeQuery();
            rSet.next();
            count = rSet.getInt(1);
        }catch (SQLException e){
            e.printStackTrace();
        }finally {
            if (rSet != null){
                try {
                    rSet.close();
                    rSet = null;
                }catch (Exception ex){
                    ex.printStackTrace();
                }
            }
            if (pStatement != null){
                try {
                    pStatement.close();
                    pStatement = null;
                }catch (Exception ex){
                    ex.printStackTrace();
                }
            }
        }
        return count;
    }

InformationServlet.java


package servlet;

import dao.InformationDAO;
import entity.Information;
import util.PageBean;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

@WebServlet(name = "InformationServlet", value = "/InformationServlet")
public class InformationServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    //跳转资源
    private String uri;
    //Costructor of the object.
    public InformationServlet(){
        super();
    }
    //Destruction of the servlet
    @Override
    public void destroy() {
        super.destroy(); // Just puts "destroy" string in log  //log 日志;
        // Put your code here
    }
    /**
     * The doGet method of the servlet. 
* * This method is called when a form has its tag value method equals to get. * * @param request * the request send by the client to the server * @param response * the response send by the server to the client * @throws ServletException * if an error occurred * @throws IOException * if an error occurred */
@Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //设置编码 request.setCharacterEncoding("UTF-8"); response.setContentType("text/html;charset=UTF-8"); //获取操作类型 String method = request.getParameter("method"); //判断 if ("add".equals(method)) add(request, response); else if ("list".equals(method)) list(request, response); else if ("search".equals(method)) search(request, response); else if ("delete".equals(method)) delete(request, response); else if ("jumpup".equals(method)) jumpup(request, response); else if ("update".equals(method)) update(request, response); } @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } // d.查找单个公司资讯 public void search(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { // 获取“当前页”参数;(当第一次访问当前页为null) String currPage = request.getParameter("currentPage"); // 获取查找的标题 String InformationTitle = request.getParameter("title"); // 判断 if (currPage == null || "".equals(currPage.trim())) { currPage = "1"; // 第一次访问,设置当前页为1; } // 转换页参数为int类型 int currentPage = Integer.parseInt(currPage); // 创建PageBean对象,设置当前页参数; PageBean pageBean = new PageBean(); pageBean.setCurrentPage(currentPage); // 创建Information对象,将标题的值加入title Information title = new Information(); title.setTitle(InformationTitle); // 调用dao对象的search方法,得到结果 InformationDAO dao = new InformationDAO(); Map<String, Object> result = dao.search(pageBean, title); if (result==null) response.getWriter().println("232323223"); // 保存 request.setAttribute("result", result); // 跳转路径 uri = "/sys/information/information.jsp"; } catch (Exception e) { e.printStackTrace(); } // 转发 //request.getRequestDispatcher(uri).forward(request, response); } /** * Initialization of the servlet.
* * @throws ServletException * if an error occurs */
@Override public void init() throws ServletException { // Put your code here } } ```java package entity; //entity实体 //公司资讯类 public class Information { private int id; //ID private String title; //标题 private String author; //作者 private String content; //内容 private String date; //发布时间 public int getId() { return id; } public void setId(int id) { this.id = id; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getAuthor() { return author; } public void setAuthor(String author) { this.author = author; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } public String getDate() { return date; } public void setDate(String date) { this.date = date; } } entity.Information.java Inforamtion实体

util.DBHelper和util.PageBean(这俩个应该没有问题,其他功能都调用过都正常运行)

package util;

import java.sql.Connection;
import java.sql.DriverManager;

public class DBHelper {
    private static final String driver = "com.mysql.jdbc.Driver";
    private static final String url = "jdbc:mysql://localhost:3306/red_wine?useSSL=false&useUnicode=true&characterEncoding=UTF-8";
    private static final String username = "root";
    private static final String password = "newpassword";
    private static Connection conn = null;
    static {
        try {
            Class.forName(driver);
        }catch (Exception ex){
            ex.printStackTrace();
        }
    }
    public static Connection getConnection() throws Exception{
        if (conn==null){
            conn = DriverManager.getConnection(url,username,password);
            return conn;
        }
        return conn;
    }
}



package util;

public class PageBean {
    private int currentPage = 1;    //current现在的;当前的  //当前页,默认显示第一页
    private int pageCount = 6;      //每页显示的行数(查询返回的行数),默认每页显示6行
    private int totalCount;         //总记录数
    private int totalPage;          //总页数=总记录数/每页显示的行数(+1)

    public int getTotalPage() {
        if (totalCount % pageCount == 0){
            totalPage = totalCount / pageCount;
        }else {
            totalPage = totalCount / pageCount + 1;
        }
        return totalPage;
    }

    public int getCurrentPage() {
        return currentPage;
    }

    public void setCurrentPage(int currentPage) {
        this.currentPage = currentPage;
    }

    public int getPageCount() {
        return pageCount;
    }

    public void setPageCount(int pageCount) {
        this.pageCount = pageCount;
    }

    public int getTotalCount() {
        return totalCount;
    }

    public void setTotalCount(int totalCount) {
        this.totalCount = totalCount;
    }

    public void setTotalPage(int totalPage) {
        this.totalPage = totalPage;
    }
}

数据库

img

报错信息

img

  • 写回答

4条回答 默认 最新

  • CSDN专家-sinJack 2023-04-01 13:20
    关注

    错误提示的意思是只有两个占位符,但是你给三个占位符赋值,导致越界异常。
    占位符是不能加单引号或者双引号的,否则就会被解析为字符串。

    String sql = "select * from Information where title like concat('%','?','%') limit ?,?;";
    改为:
    String sql = "select * from Information where title like concat('%',?,'%') limit ?,?;";
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

问题事件

  • 系统已结题 4月9日
  • 已采纳回答 4月1日
  • 创建了问题 4月1日

悬赏问题

  • ¥15 stm32f407使用DMA问题
  • ¥15 您好 这个API接口该怎么弄 网站搭建好了 API也有 现在就不知道该怎么填写API 不知道怎么用
  • ¥88 用uniapp写一个多端的程序,用到高德地图,用高德的JSAPI吗?
  • ¥20 关于#c++#的问题:水果店管理系统
  • ¥30 dbLinq最新版linq sqlite
  • ¥20 对D盘进行分盘之前没有将visual studio2022卸载掉,现在该如何下载回来
  • ¥15 完成虚拟机环境配置,还有安装kettle
  • ¥15 2024年全国大学生数据分析大赛A题:直播带货与电商产品的大数据分析 问题5. 请设计一份优惠券的投放策略,需要考虑优惠券的数量、优惠券的金额、投放时间段和投放商品种类等因素。求具体的python代码
  • ¥15 有人会搭建生鲜配送自营+平台的管理系统吗
  • ¥15 用matlab写代码