当我试图从TableView中删除一行时,会得到以下错误
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '[value: 3]' at line 1我想要的是:一旦从TableView中选择了一行,我想从数据库中删除它。
@FXML
void delete(ActionEvent event) {
try {
int pos;
pos = (int) tabelCustomers.getSelectionModel().getSelectedIndex();
Customers c;
c = tabelCustomers.getItems().get(pos);
SimpleIntegerProperty idc = c.idc;
String query;
query = "DELETE FROM customers WHERE customers.idc = " + idc;
try (Statement stm = cnx.createStatement()) {
stm.executeUpdate(query);
}
} catch (SQLException ex) {
Logger.getLogger(CustomersTableController.class.getName()).log(Level.SEVERE,
null, ex);
}
}我遗漏了什么?我已经尝试了很多可能的解决方案,但都没有效果。基本上,当用户单击表中的行,然后单击"remove“按钮时,应该从表和DB中删除该行。
提前谢谢。
发布于 2020-01-10 15:04:08
SimpleIntegerProperty idc = c.idc;
String query = "DELETE FROM customers WHERE customers.idc = " + idc;当一个Object (不是String)用于字符串连接时,它会通过调用toString()来自动转换为String。SimpleIntegerProperty的字符串表示形式不仅仅是它的值,这意味着您的查询最终看起来如下所示:
DELETE FROM customers WHERE customers.idc = IntegerProperty [bean: <some_instance>, name: idc, value: 42]这显然是无效的SQL。您需要提取属性的值,并将其用作查询的一部分。但是,在创建SQL查询时,首先不应该使用字符串连接。相反,您应该使用带有参数的PreparedStatement。例如:
String query = "DELETE FROM customers WHERE customers.idc = ?";
try (PreparedStatement ps = cnx.prepareStatement(query)) {
ps.setInt(1, idc.get());
ps.executeUpdate();
}https://stackoverflow.com/questions/59681767
复制相似问题