参数索引超出范围(1>参数个数,即0),如何避免?

问题描述:

Java代码参数索引超出范围(1>参数个数,即0),如何避免?

我一直在尝试更新选定的行值,但我得到的参数索引超出了约束的异常。有什么建议么?声明是正确的,任何人都可以解释它为什么会发生?

public class Editbook extends HttpServlet { 
    private static final long serialVersionUID = 1L; 
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 
     PrintWriter out = response.getWriter(); 
     try { 
      String booktitle = request.getParameter("booktitle"); 
      String author = request.getParameter("author"); 
      String category = request.getParameter("category"); 
      String pages = request.getParameter("pages"); 
      String desc = request.getParameter("description"); 
      String isbn = request.getParameter("isbn"); 

      Connection con = Logincheck.getConnection(); 
      PreparedStatement ps = con.prepareStatement("update books set title ='"+booktitle+"', author ='"+author+"', category ='"+category+"', pages ='"+pages+"', description ='"+desc+"' where isbn ='"+isbn+"'"); 

      ps.setInt(1, Integer.parseInt(isbn)); 
      ps.setString(2, booktitle); 
      ps.setString(3, author); 
      ps.setString(4, category); 
      ps.setInt(5, Integer.parseInt(pages)); 
      ps.setString(6, desc); 

      int i = ps.executeUpdate(); 
      out.println("updated"); 
      System.out.println(i + "updated"); 
     } catch (Exception e) {System.out.println(e);} 

    } 

} 
+2

您正在混合连接和SQL参数。 –

PreparedStatement,你直接把参数的值,并且不使用任何?。所以,当你写

ps.setInt(1, Integer.parseInt(isbn)); 

这种说法是与指定的值替换的?第一次出现。但是由于没有?,它给出了参数索引超出界限的异常。

如果您要创建PreparedStatement并为其提供参数,则必须在SQL中相应标记它。现在你连接了一个完整的SQL,然后你不能提供任何参数给它,因为没有参数需要提供。相反,每个参数都被标记为?在你的SQL中。

你的代码应该在的线(注意参数的顺序)的东西:

Connection con = Logincheck.getConnection(); 
PreparedStatement ps = con.prepareStatement("update books set title = ?, author = ?, category = ?, pages = ?, description = ? where isbn = ?"); 

ps.setString(1, booktitle); 
ps.setString(2, author); 
ps.setString(3, category); 
ps.setInt(4, Integer.parseInt(pages)); 
ps.setString(5, desc); 
ps.setInt(6, Integer.parseInt(isbn)); 

编辑:在另一方面。使用参数我在这里发布的方式比连接一个完整的SQL字符串更加优选,因为它会使您的代码更少倾向于SQL代码注入。

问题是您的HttpServletRequest没有参数。所以,你不能访问他们在这里

String booktitle = request.getParameter("booktitle"); 
      String author = request.getParameter("author"); 

我会建议检查是否请求包含第一参数,然后访问它们:

if (request.getParameterMap().containsKey("booktitle")) { 
      String booktitle = request.getParameter("booktitle"); 
     } 

并告诉你如何建立你的POST请求。

+0

['getParameter()'](http://docs.oracle.com/javaee/6/api/javax/servlet/ServletRequest.html#getParameter(java.lang.String))如果参数不返回null不存在。 – Andreas