问答详情
源自:2-6 列表查询

sql拼接

我的参数没乱码,sql却成了select ID,COMMAND,DESCRIPTION,CONTENT from message where 1=1 and COMMAND = ?   select ID,COMMAND,DESCRIPTION,CONTENT from message where 1=1 and DESCRIPTION like '%' ? '%' 参数就没替换上去,这是为什么?那位大神能帮我解决一下

提问者:模棱0 2016-10-24 20:45

个回答

  • 模棱0
    2016-10-26 21:53:41

    req.setCharacterEncoding("utf-8");

    try {

    String command = req.getParameter("command");

    String description = req.getParameter("description");

    req.setAttribute("command", command);

    req.setAttribute("description", description);

    Class.forName("com.mysql.jdbc.Driver");

    Connection connection = (Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/micro_message", "root", "root");

    StringBuilder sql = new StringBuilder("select ID,COMMAND,DESCRIPTION,CONTENT from MESSAGE where 1=1");

    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 statement = (PreparedStatement) connection.prepareStatement(sql.toString());

    System.out.println(paramList.size());

    for (int i = 0; i < paramList.size(); i++) {

    statement.setString(i+1, paramList.get(i));//sql语句中出现的?是从第一个开始数

    }

    System.out.println(sql.toString());

    ResultSet resultSet = statement.executeQuery();

    List<Message> messageList = new ArrayList<Message>();

    while(resultSet.next()){

    Message message = new Message();

    messageList.add(message);

    message.setId(resultSet.getString("ID"));

    //System.out.println(resultSet.getString("ID"));

    message.setCommand(resultSet.getString("COMMAND"));

    message.setDescription(resultSet.getString("DESCRIPTION"));

    message.setContent(resultSet.getString("CONTENT"));

    }

    req.setAttribute("messageList", messageList);


  • qq_我不高兴了_03822679
    2016-10-25 11:01:54

    把代码贴出来