我已经在ms access中创建了一个表。我在MS-access中将ID的数据类型设置为“自动编号”。在Java中,当我尝试更新记录时。 netBeans IDE给我“标准表达式中数据类型不匹配”的错误。
但是,当我更改不在表中的ID号时,它的效果很好。代码如下。

String sql = "Update table1 set price ='" + txtPrice.getText() + "', quantity='" + txtQuantity.getText() + "', description='" + txtDescription.getText() + "' where id= " + txtid.getText() + "";
        try {
             pst = conn.prepareStatement(sql);
            pst.executeUpdate();
            JOptionPane.showMessageDialog(null, "Updated");
            UpdateJTable();
        } catch (Exception e) {

            JOptionPane.showMessageDialog(null, e);
        }

最佳答案

我认为您可能也会混淆常规Statement和PreparedStatement对象。 PreparedStatement使您有机会使用占位符(在很多sql语句中可能会看到的?),并使PreparedStatement为您做更多的工作。

尝试像这样编写您的sql语句:

update table1 set price = ?, quantity = ?, description = ? where id = ?


然后,使用PreparedStatement对象,您将执行以下操作:

pStmt.setInteger(1, Integer.valueOf(txtPrice.getText())


对于每个参数。自从我直接使用PreparedStatement以来已经有几年了,但是如果提供内存,则参数基于1。

但是您的基本问题是铸造。使用PreparedStatement可以使您的代码更整洁(并且更安全)。

10-08 09:02
查看更多