我正在尝试修复此问题一段时间,但是找不到或修复代码。当我在方法中添加自动生成的“ 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);
}
}
答案 0 :(得分:1)
您正确使用了一条准备好的语句,但是应该在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
解释为引用列,表等名称。通过使用准备好的语句(您正在做的事情),您可以让数据库处理值的正确转义。