我是Java的新手,在Java项目中,每当单击“销售”按钮并自动更新表时,我想从数据库表Item_detail的“可用”字段中减去一个名为Quantity(q_field)的文本框值。我写了一些代码,但是没有用。我的代码是:

private void jButton6ActionPerformed(java.awt.event.ActionEvent evt) {

if(!p_field.getText().isEmpty() && !b_field.getText().isEmpty() && !m_field.getText().isEmpty() && !sell_field.getText().isEmpty() && !c_field.getText().isEmpty()){
int a=Integer.parseInt(q_field.getText().trim());

String sql1="update Item_detail set Available=Available-'a'    where P_name=? and Manuf_name =? and Model_no=?";
String sql2="insert into Sell (`S_id`,`P_name`,`Manuf_name`,`Model_no`,`Date`,`Quantity`,`S.p`,`Cost_price`) values(?,?,?,?,?,?,?,?)";
try{
    pst=(PreparedStatement) con.prepareStatement(sql1);

    pst.setString(1, p_field.getText());
    pst.setString(2, b_field.getText());
    pst.setString(3, m_field.getText());
    pst.setString(4, q_field.getText());
    pst.executeUpdate();

    JOptionPane.showMessageDialog(null, "Product sold  successfully");
    update_table();

    }catch(Exception e){
    JOptionPane.showMessageDialog(null, e);


我无法理解什么是“ sql1”的正确sql代码。请帮忙

最佳答案

sql1应为:

String sql1="update Item_detail
                   set Available=Available-?
             where
                   P_name=?
               and Manuf_name =?
               and Model_no=?";


并将值设置为pst查询以包含变量a的值,如下所示:

pst=(PreparedStatement) con.prepareStatement(sql1);

pst.setInt(1, a);
pst.setString(2, ...
...
pst.executeUpdate();


但是,请确保只为查询中该数量的地方持有人设置值。否则,将发生占位符计数不匹配的情况,并抛出SQLException。

10-06 12:52
查看更多