2017-04-04 54 views
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參數。 –

回答

2

PreparedStatement,你直接把參數的值,並且不使用任何?。所以,當你寫

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

這種說法是與指定的值替換的?第一次出現。但是由於沒有?,它給出了參數索引超出界限的異常。

2

如果您要創建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代碼注入。

-1

問題是您的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

相關問題