繁体   English   中英

使用 Java Servlet/jsp 将产品添加到数据库

[英]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 ) 语句,例如INSERTUPDATEDELETE ,您应该使用executeUpdateexecute

此外,您的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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM