【问题标题】:Java sql update error : data type mismatchJava sql更新错误:数据类型不匹配
【发布时间】:2012-06-03 05:41:20
【问题描述】:

我在 ms 访问中创建了一个表。我在 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);
        }

【问题讨论】:

  • 如果您收到错误,最好发布堆栈跟踪。

标签: java sql netbeans


【解决方案1】:

我认为您可能也会混淆常规 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 还可能使您的代码更简洁(更安全)。

【讨论】:

    【解决方案2】:

    我假设 price 和 quantity 列是整数,因此您不需要引用它们。

    试试下面的sql:

    String sql = "Update table1 set price =" + txtPrice.getText() + ",
                  quantity=" + txtQuantity.getText() + ", description='" +
                  txtDescription.getText() + "' where id= " + txtid.getText() + "";
    

    请注意价格和数量中缺少单引号

    【讨论】:

    • Suraj chandran 执行此操作后出现另一个错误,错误是“参数太少”,不是这个。
    【解决方案3】:

    首先尝试在您的 id 字段中使用类型转换。喜欢:

    int id = Integer.parseInt(txtid.getText());
    

    然后执行查询:

    String sql = "Update table1 set price ='" + txtPrice.getText() + "', quantity='" +
                  txtQuantity.getText() + "', description='" + txtDescription.getText() + "' 
                  where id= " + id + "";
    

    【讨论】:

      【解决方案4】:

      对于您得到的参数太少错误 - 仔细检查您查询中的字段名称。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-04-12
        • 2012-08-23
        • 2015-10-31
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多