使用控制器中的prepareStatement将多行插入表中失败

时间:2016-02-11 16:35:39

标签: sql jsp model-view-controller jdbc prepared-statement

我的代码如下所示。我试图从JSP页面获取多个输入并将它们插入到控制器中的SQL中。但它不起作用。有人能指出我正确的方向吗?

String price[] = request.getParameterValues("price");
String isbn[] = request.getParameterValues("isbn");
String title[] = request.getParameterValues("title");
String authors[] = request.getParameterValues("authors");

HttpSession session = request.getSession();
int number = (Integer)session.getAttribute("number");

for(int i = 0; i<number;i++){
     String queryAdd = "INSERT INTO books (price, isbn, title,authors) values" + "(?,?,?,?)";
     PreparedStatement stmt = conn.prepareStatement(queryAdd);
     stmt.setFloat(1, Float.valueOf(price[i]));
     stmt.setString(2, isbn[i]);
     stmt.setString(3, title[i]);
     stmt.setString(4, authors[i]);
     int result = stmt.executeUpdate(queryAdd);
     out.println(result);
     if(result<=0){
         RequestDispatcher rd = request.getRequestDispatcher("/WEB-INF/Views/error.jsp");
         rd.forward(request, response);
     }
}
conn.close();
RequestDispatcher rd = request.getRequestDispatcher("/WEB-INF/Views/successful.jsp");
rd.forward(request, response);

我的jsp页面在这里:

<form action="addBook.htm" method="post">
    <table style="border:1px solid red; border-collapse: collapse">
        <tr>
            <th>ISBN</th>
            <th>Book Title</th>
            <th>Authors</th>
            <th>Price</th>
        </tr>
        <c:forEach var="i" begin="1" end="${sessionScope.number}" step="1">
            <tr>
                <td><input type="text" name="isbn"/></td>
                <td><input type="text" name="title"/></td>
                <td><input type="text" name="authors"/></td>
                <td><input type="text" name="price"/></td>
            </tr>
        </c:forEach>
        <tr>
            <td colspan="4" style="text-align: center">
                <input type="submit" name="submit" value="Add Books" />
                <input type="hidden" name="action" value="addSubmit"/>
             </td>
        </tr>
    </table>
</form>

1 个答案:

答案 0 :(得分:1)

您的PreparedStatement调用存在问题:

 String queryAdd = "INSERT INTO books (price, isbn, title,authors) values (?,?,?,?)";
 PreparedStatement stmt = conn.prepareStatement(queryAdd);
 stmt.setFloat(1, Float.valueOf(price[i]));
 stmt.setString(2, isbn[i]);
 stmt.setString(3, title[i]);
 stmt.setString(4, authors[i]);

到目前为止很好 - 但不是下一行:

 int result = stmt.executeUpdate(queryAdd);

这会调用executeUpdate的{​​{1}}方法 - 传入SQL并忽略所有参数集。将其更改为

Statement

你可能会看到一些结果。

有关您的代码的更多说明:

  • 如果数组中没有太多项,则应考虑使用addBatch()和executeBatch()来减少SQL往返。
  • 关闭您的陈述/使用try-with-resource