[英]Add a product to a Database using Java Servlet/jsp
你能幫我解決這個問題嗎? 我找不到正在發生的事情。 我正在使用 Java Servlets 和 Z2D7FCA4F5778E4B294B606914719 執行 web 應用程序。
當我嘗試添加產品時,它在 URL 中顯示: http://localhost:8080/ProductMaintenanceMdy/add?action=add&code=8768&description=mylove&price=15.55&Add+product=
由於它顯示了 URL 中輸入的數據,這意味着 addProduct.jsp 中的表單正在工作,但它不會將產品保存在數據庫中。
你能檢查我添加的servlet代碼、映射代碼和查詢function是否正確? 別客氣,我是初學者。
//添加產品的Servlet代碼
else if (action.equals("addProducts")) // this is for action inside display
{
url= "/addProducts.jsp";
}
else if (action.equals("add")) //this is for add inside sddProducts
{
String code= request.getParameter("code");
String description= request.getParameter("description");
Double price=Double.parseDouble(request.getParameter("price"));
Product p= new Product();
p.setCode(code);
p.setDescription(description);
p.setPrice(price);
ProductDB.insertProduct(p); //implemented it inside productDB.java
url="/addProducts.jsp";
}
// Web xml 映射部分用於添加
<servlet-mapping>
<servlet-name>ProdMaintAppServlet</servlet-name>
<url-pattern>/add</url-pattern>
</servlet-mapping>
// ProductDB 中的方法(用於數據庫查詢功能的類)
public static void insertProduct(Product p) {
ConnectionPool pool = ConnectionPool.getInstance();
Connection connection = pool.getConnection();
PreparedStatement ps = null;
ResultSet rs = null;
String query=" INSERT INTO productsMaintenance VALUES( '"+ p.getCode()+"','"+ p.getDescription()+"','"+ p.getPriceCurrencyFormat()+"' ) ";
try {
ps = connection.prepareStatement(query);
rs = ps.executeQuery();
}
catch (SQLException e) {
System.err.println(e);
} finally {
DBUtil.closeResultSet(rs);
DBUtil.closePreparedStatement(ps);
pool.freeConnection(connection);
}
}
您可以使用調試器找出根本原因。 除此之外,下面給出了一些最佳實踐,它們也可以幫助您擺脫問題。
對於 SQL 數據操作語言 ( DML ) 語句,例如INSERT
、 UPDATE
或DELETE
,您應該使用executeUpdate或execute 。
此外,您的PreparedStatement
實現與Statement
沒有什么不同,即您實際上沒有利用PreparedStatement
的功能和好處。 它應該像
String query = "INSERT INTO productsMaintenance (Code, Description, PriceCurrencyFormat) VALUES (?, ?, ?)";
ps = conn.prepareStatement(query);
ps.setString (1, p.getCode());
ps.setString (2, p.getDescription());
ps.setString (3, p.getPriceCurrencyFormat());
// execute the PreparedStatement
ps.execute();
這樣,您可以防止SQL 注入的嘗試,並且您可以擺脫在每個數據之前和之后顯式插入'
。
檢查此以了解更多信息。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.