我试图修复这个问题一段时间,但找不到或修复代码。当我添加方法中自动生成的“id”时触发错误。
private void btnUpdateActionPerformed(java.awt.event.ActionEvent evt) {
try {
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/inventory?useTimezone=true&serverTimezone=UTC", "root", "ichigo197328");
int row = jTable1.getSelectedRow();
String value = (jTable1.getModel().getValueAt(row, 0).toString());
String sql = "UPDATE category SET category_name = ? WHERE category_id = "+ value;
PreparedStatement pstmt = conn.prepareStatement(sql);
pstmt.setString(1, CategoryNameField.getText());
pstmt.executeUpdate();
DefaultTableModel model = (DefaultTableModel)jTable1.getModel();
model.setRowCount(0);
JOptionPane.showMessageDialog(null, "Record Updated Successfully ");
DisplayTable();
conn.close();
}
catch(Exception e) {
JOptionPane.showMessageDialog(null, e);
}
}
最佳答案
您正确地使用了准备好的语句,但您应该在 WHERE
子句中使用位置参数而不是串联:
String sql = "UPDATE category SET category_name = ? WHERE category_id = ?";
PreparedStatement pstmt = conn.prepareStatement(sql);
pstmt.setString(1, CategoryNameField.getText());
pstmt.setString(2, value);
pstmt.executeUpdate();
错误的确切原因与您的 WHERE
子句有关,该子句将 category_id
字符串列与未转义的字符串文字进行比较,例如
WHERE category_id = some_value -- should be 'some_value'
SQL 会将 some_value
解释为引用列、表等名称。通过使用准备好的语句(您已经在这样做),您可以让数据库处理值的正确转义。
关于java - 'CA1001' 中的未知列 'where clause',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59341266/