在 Eclipse 中使用 UPDATE - SET - WHERE 方法更新 MySQL 数据库时出错

Error when updating MySQL database using UPDATE - SET - WHERE method in Eclipse

我正在使用 Eclipse 制作一个程序,允许用户在每次 restocked/used 时更新化学品的数量,这要求他们输入化学品的 ID 和他们想要的数量 add/subtract。然后执行查询以在数据库中搜索化学品的 ID,并相应地更新其数量。

但是,我很难更新音量。我尝试将 MySQL 的更新语句从 this website 修改为 SET volume = volume + amount added, WHERE chemical ID = ID by the user entered;但是,我的代码中似乎存在一些语法错误,更具体地说是在 UPDATE - SET - WHERE 行:

public void IDEnter() {
    try {
        Class.forName("com.mysql.cj.jdbc.Driver");
        Connection con = DriverManager.getConnection("jdbc:mysql://localhost:8889/StockControlSystem","root","root");
        Statement stmt = con.createStatement();
        String sql = "Select * from Chemicals where `Chemical ID` ='" + txtChemical_ID.getText()+"'";
        ResultSet rs = stmt.executeQuery(sql);
        if(rs.next()) {
            stmt.executeUpdate("UPDATE Chemicals" + "SET `Volume` = rs.getInt(Volume) + Integer.parseInt(AmountAdded.getText()) WHERE `Chemical ID` in (txtChemical_ID.getText())");
        }
        else {
            JOptionPane.showMessageDialog(null, "Invalid chemical ID");
            txtChemical_ID.setText(null);
        }
    } catch(Exception exc) {
        exc.printStackTrace();
    }
}

由于我对 MySQL 还是个新手,有人可以帮我改正吗?非常感谢您的帮助!

我认为您的问题可能出在“rs.getInt(音量)”

你的:

    "UPDATE Chemicals" + "SET `Volume` = rs.getInt(Volume)
+ Integer.parseInt(AmountAdded.getText()) 
WHERE `Chemical ID` in (txtChemical_ID.getText())"

你能试试这个吗:

 "UPDATE Chemicals" + "SET `Volume` = " + 
Integer.parseInt(AmountAdded.getText()) + " 
WHERE `Chemical ID` in (" + (txtChemical_ID.getText()) +")"

您的整个查询格式不正确。将您的代码更改为:

stmt.executeUpdate("UPDATE Chemicals SET Volume = " +
 rs.getInt(Volume) + Integer.parseInt(AmountAdded.getText())
 + " WHERE Chemical_ID in (" + txtChemical_ID.getText() +  ")");

在查询中定义列名时不能使用 ' 单引号。单引号用于字符串值!

不过,这并不是最好的方法。使用 PreparedStatement!

这样:

String updateString = "UPDATE Chemicals SET Volume = ? WHERE Chemical_ID in (?)"; // Creation of the prepared statement, the ? are used as placeholders for the values
PreparedStatement preparedStatement = con.prepareStatement(updateString);
preparedStatement.setInt(1, rs.getInt(Volume) + Integer.parseInt(AmountAdded.getText())); // Setting the first value
preparedStatement.setString(2, txtChemical_ID.getText()); // Setting the second. I am supposing that this txtChemical_ID textField has values seperated by commas, else this will not work!
preparedStatement.executeUpdate();

如果您需要为 PreparedStatement 阅读更多内容,那里有很多很棒的 resources。它们还可以防止 SQL 注入。