首页 > 解决方案 > Java FXML - NetBeans - 从表中删除 - MySQL

问题描述

当我尝试从中删除一行时出现以下错误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);
    }
}

我错过了什么?我尝试了很多可能的解决方案,没有任何效果。基本上,当用户单击表中的行然后单击“删除”按钮时,应从表和数据库中删除该行。

提前致谢。

标签: mysqljavafxnetbeans

解决方案


SimpleIntegerProperty idc = c.idc;
String query = "DELETE FROM customers WHERE customers.idc = " + idc;

当在字符串连接中使用Objecta (不是 a )时,它会通过调用它自动转换为 a 。的字符串表示不仅仅是它的值,这意味着您的查询最终看起来像:StringStringtoString()SimpleIntegerProperty

DELETE FROM customers WHERE customers.idc = IntegerProperty [bean: <some_instance>, name: idc, value: 42]

这显然不是有效的 SQL。您需要提取属性的值并将其用作查询的一部分。但是,首先创建 SQL 查询时不应使用字符串连接。您应该改为使用PreparedStatement带有参数的 a。例如:

String query = "DELETE FROM customers WHERE customers.idc = ?";
try (PreparedStatement ps = cnx.prepareStatement(query)) {
  ps.setInt(1, idc.get());
  ps.executeUpdate();
}

推荐阅读