( )
2019-11-21 12:48
采纳率: 100%
浏览 434
已采纳

为什仫我使用servlet查询数据库得不到数据?

使用servlet查询数据库,得不到数据库的数据,我是用断点测试,直接执行request.getRequestDispatcher("/second.jsp").forward(request,response);语句,我用request.setAttribute("list",list);保存数据,在jsp文件用 List list = (List)request.getAttribute("list");时,等到list为null

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=utf-8");
        request.setCharacterEncoding("utf-8");
        try {
            Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
            Connection connection = DriverManager.getConnection("jdbc:sqlserver://localhost:49680;DatabaseName=student", "sa", "123456");
            Statement statement = connection.createStatement();
            ResultSet resultSet = statement.executeQuery("select * from dbo.scores");
            List<Stu> list = new ArrayList<Stu>();
            while (resultSet.next()) {
                Stu stu = new Stu();
                String sno = resultSet.getString("学号");
                String sname = resultSet.getString("姓名");
                String sex = resultSet.getString("性别");
                int grade = resultSet.getInt("得分");
                stu.setSno(sno);
                stu.setSname(sname);
                stu.setSex(sex);
                stu.setGrade(grade);
                list.add(stu);
            }
            request.setAttribute("list",list);
            PrintWriter out = response.getWriter();
            out.println("ajiaaaaa");
            int i =1;
            resultSet.close();
            statement.close();
            connection.close();
        }catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e){
            e.printStackTrace();
        }
        request.getRequestDispatcher("/second.jsp").forward(request,response);
    }
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • FFone- Java-er 2019-11-21 13:00
    已采纳

    打过断点了应该可以在request.setAttribute("list",list)设置的时候可以看到list有没有值的啊,如果存的时候都没有jsp肯定也得不到这个值的。最好是用数据库连接工具啥的,执行一下查询sql,看是不是条件没匹配。使用setAttribute("list",list)类似的方法时最好是不要直接用list,带上信息,像这个可以写setAttribute("stuInfoList",list)

    已采纳该答案
    打赏 评论
  • cap_jack_sp 2019-11-21 13:21

    数据库里表的列名是中文的?

    打赏 评论

相关推荐 更多相似问题