我有一个数据库和一个名为itemDetail
的表,它包含两个字段:itemName
和quantity
使用jsp
如何从数据库中扣除/更新取决于我输入的数字?
示例
初始数量= 100 Html表单数量= 1 SQL语句应该更新数据库 数量 - html表单数量 数据库中的新数量= 99
请帮帮我。
感谢。
我的编码样本
<%
String iName = request.getParameter("itemName");
String Qty = request.getParameter("quantity");
String price = request.getParameter("price");
//out.print("itemName");
//out.print("quantity");
//out.print("price");
%>
<%-- <jsp:setProperty name="MrBeanA" property="itemName" />
<jsp:setProperty name="MrBeanA" property="Quantity" /> --%>
<%@ page import = "java.sql.Connection"%>
<%@ page import = "java.sql.DriverManager"%>
<%@ page import = "java.sql.Statement"%>
<%
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con = DriverManager.getConnection("jdbc:odbc:Project");
Statement s = con.createStatement();
int yrwish = s.executeUpdate( "insert into Inventory (itemName, Qty, Price) values ('" + iName + "','" + Qty + "','" + price + "')");
s.close();
con.close();
%>
<%
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con1 = DriverManager.getConnection("jdbc:odbc:Project");
Statement delete = con.createStatement();
int yrwish2 = delete.executeUpdate("UPDATE itemDetail SET quantity =("+quantity-Qty+")WHERE itemName=+iName");
delete.close();
con1.close();
%>
错误 在jsp文件中的第44行:/myjsp/Confirm.jsp发生错误 生成的servlet错误: 数量无法解决
是
<%
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con1 = DriverManager.getConnection("jdbc:odbc:Project");
Statement delete = con.createStatement();
int yrwish2 = delete.executeUpdate("UPDATE itemDetail SET quantity =("+quantity-Qty+")WHERE itemName=+iName");
delete.close();
con1.close();
%>
答案 0 :(得分:-1)
如果您想在同一页面上执行此操作,请使用jQuery Ajax
否则使用表单获取输入并在提交时运行Servlet,您可以在其中更新数据库here
在表单提交时,Servlet将运行在'action'属性
中Servlet代码:未经过测试
import java.io.*;
import java.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class MyServlet extends HttpServlet {
public void doPost(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
String name = req.getParameter("itemName");
int val = Integer.parseInt(req.getParameter("itemq").trim());
Connection con = null;
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost/test?" +
"user=minty&password=greatsqldb");
编辑:
Statement stmt = con.createStatement();
ResultSet rs1 = stmt.executeQuery("select quantity from itemDetail where itemName = "+iName);
rs1.next();
int quantity = rs1.getInt("quantity"); //column label in database
stmt.executeUpdate("UPDATE itemDetail SET quantity = "+(quantity - val)+" where itemName = "+name);
con.commit();
}
catch (Exception e) {
}
finally {
if (con != null)
con.close();
}
}
}
编辑:参考OP的错误:
int yrwish2 = delete.executeUpdate("UPDATE itemDetail SET quantity = (quantity - "+Qty+") WHERE itemName="+iName);
希望它有所帮助!