输入查询条件会报参数索引超出范围的错误
java.sql.SQLException: Parameter index out of range (1 > number of parameters, which is 0).
两个百分号之间加了空格,
控制台打印的paramerList为??????是不是表示页面的参数没有传过去?
package servlet; import java.io.IOException; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import bean.Message; /** * @author 570 * */ public class ListServlet extends HttpServlet { /** * */ private static final long serialVersionUID = 1L; @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { try { String command = req.getParameter("command");//从页面拿到参数 String description =req.getParameter("description"); Class.forName("com.mysql.jdbc.Driver"); Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb?characterEncoding=utf8&useSSL=true","root","root"); // String sql ="SELECT ID,COMMAND,DESCRIPTION,CONTENT FROM imooc_mybatis_list"; //where 1=1 用于语句拼接。。不明所以 StringBuilder sql = new StringBuilder("select ID,COMMAND,DESCRIPTION,CONTENT from imooc_mybatis_list where 1=1"); PreparedStatement ps = conn.prepareStatement(sql.toString()); // PreparedStatement ps = conn.prepareStatement(sql); //多条件查询时,利用List做缓冲,保存查询参数,然后再循环赋值 List<String> paramerList = new ArrayList<String>(); //语句拼接如果查询的指令非空且非空字符串则执行语句拼接查询 if (command!=null&&!"".equals(command.trim())) { sql.append(" and COMMAND=? "); paramerList.add(command); } if (description!=null&&!"".equals(description.trim())) { sql.append("and DESCRIPTION like '%' ? '%' "); paramerList.add(description); } //把页面上的语句拿给要送到数据库查询的ps中 for (int i = 0; i < paramerList.size(); i++) { System.out.println(paramerList.get(i)); ps.setString(i+1, paramerList.get(i));//错误指向这一行 } ResultSet rs = ps.executeQuery(); List<Message> messageList = new ArrayList<Message>(); while (rs.next()) { Message message = new Message(); messageList.add(message); message.setId(rs.getString("ID")); message.setCommand(rs.getString("COMMAND")); message.setDescription(rs.getString("DESCRIPTION")); message.setContent(rs.getString("CONTENT")); } req.setAttribute("messageList", messageList); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } req.getRequestDispatcher("/WEB-INF/jsp/list.jsp").forward(req, resp); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { this.doGet(req, resp); } }