如何从mysql数据库中减去输入? 让我们说我正在做一个帐单和库存系统。因此,当用户在jtextfield上输入数量时,它会从表中减去。 将附加GUI。
现在,我写了这个方法
public boolean updateBill(Bill bi) {
boolean success = false;
dbController db = new dbController();
PreparedStatement ps;
try {
myConn = DriverManager.getConnection("jdbc:mysql://localhost:3306/ooadp?useSSL=false", "root", "pass");
Statement myStatement = myConn.createStatement();
String sql = "UPDATE medicalproduct SET quantity = quantity - ? WHERE productID = ?, productName = ?, dosage = ?, price = ?, status = ?" ;
myStatement.executeUpdate(sql);
myConn.close();
} catch (Exception e) {
e.printStackTrace();
}
return success;
}
但后来我不知道在actionPerform上写什么以及如何将我的jtextfield链接到sql查询。
答案 0 :(得分:0)
你的sql语句无论如何都是无效的...但如果是对的,你想要做的就是从jTextField中指定的值中减去数据库中的字段
//For example quantity -= txtfieldValue;
如果你想要的话。您可以查询字段的值,进行减法,然后最后更新字段。以下是仅更新数量的示例:
public void updateQuantity(String txtFieldValue,String id) throws ClassNotFoundException, SQLException{
Class.forName("com.mysql.jdbc.Driver");
System.out.println("Driver loaded!!!");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/ooadp?useSSL=false", "root", "pass");
System.out.println("Connection created!!!");
PreparedStatement pState;
String sqlRawP1 ="select quantity from medicalproduct where productID=?";//I guess medicalproduct is your table name
pState = conn.prepareStatement(sqlRawP1);
pState.setString(1, id);
ResultSet rSetQuantity = pState.executeQuery();
int countQuantity = 0;
while(rSetQuantity.next()){
countQuantity = rSetQuantity.getInt(1);//Am assumming that quantity is an integer
}
int value = Interger.parseInt(txtFieldValue);
countQuantity-= value;
String sqlRawP2 = "update medicalproduct set quantity=? where productID=?";
pState = conn.prepareStatement(sqlRawP2);
pState.setInt(1,countQuantity);
pState.setString(2, id);
pState.executeUpdate();
}
希望它能很好地工作。如果有轻微的错误,请原谅我,因为我自己没有测试过。