数据查询中文出现错误

错误:com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'and COMMAND='查询'' at line 1

protected void doGet(HttpServletRequest req,HttpServletResponse rsp) throws ServletException, IOException{
      try {
          //数据库连接
        Class.forName("com.mysql.jdbc.Driver");
        Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mybatis_demo?"
                + "useUnicode=true&characterEncoding=utf-8&user=root&password=mysql");
        
        //页面查询参数的获取
        //解决中文乱码问题
        req.setCharacterEncoding("UTF-8");
        rsp.setCharacterEncoding("uft-8");
        String command = req.getParameter("command");
        String description =req.getParameter("description");
        
        //String sql = "select ID,COMMAND,DESCRIPTION,CONTENT from MESSAGE";
        StringBuilder sql = new StringBuilder("select ID,COMMAND,DESCRIPTION,CONTENT from MESSAGE");
        List<String> paramList = new ArrayList<String>();
        if (command!=null && !"".equals(command.trim())) {
            sql.append(" and COMMAND=? ");
            paramList.add(command);
        }
        
        if (description!=null&&!"".equals(description.trim())) {
            sql.append(" and DESCRIPTION like '%'?'%' ");
            paramList.add(description);
        }
        
        PreparedStatement pStatement= conn.prepareStatement(sql.toString());
        for (int i = 0; i < paramList.size(); i++) {
            pStatement.setString(i+1, paramList.get(i));
        }
        ResultSet rs = pStatement.executeQuery();
        List<Message> messagelist = new ArrayList<Message>();
        while(rs.next()){
            Message message = new Message();
            message.setId(rs.getInt("ID"));
            message.setCommand(rs.getString("COMMAND"));
            message.setDescription(rs.getString("DESCRIPTION"));
            message.setContent(rs.getString("CONTENT"));
            messagelist.add(message);
        }
        req.setAttribute("messageList", messagelist);
    } catch (ClassNotFoundException e) {
        // TODO: handle exception
        e.printStackTrace();
    }catch (SQLException e) {
        // TODO: handle exception
        e.printStackTrace();
    }
    req.getRequestDispatcher("/WEB-INF/jsp/back/list.jsp").forward(req, rsp);
       
   }

Elly
浏览 2870回答 2
2回答

twocold

你在查询之前打印一下是不是在进入servlet之后就乱码了,
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

大数据