簡體   English   中英

參數索引超出范圍(1>參數數量,即0),如何避免?

[英]Parameter index out of range (1 > number of parameters, which is 0), how to avoid?

Java代碼

我一直在嘗試更新所選的行值,但是我正在獲取參數索引超出范圍的異常。 有什么建議么? 這個說法是正確的,任何人也可以解釋為什么會這樣嗎?

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);}

    }

}

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");
        }

並展示您如何構建帖子請求。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM