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 远程桌面文档内容复制粘贴,格式会变化
  • ¥15 关于#java#的问题:找一份能快速看完mooc视频的代码
  • ¥15 这种微信登录授权 谁可以做啊
  • ¥15 请问我该如何添加自己的数据去运行蚁群算法代码
  • ¥20 用HslCommunication 连接欧姆龙 plc有时会连接失败。报异常为“未知错误”
  • ¥15 网络设备配置与管理这个该怎么弄
  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题