当我尝试从 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);
}
}
我错过了什么?我尝试了很多可能的解决方案,但没有任何效果。 基本上,当用户单击表中的行,然后单击“删除”按钮时,应从表和数据库中删除该行。
提前致谢。
最佳答案
SimpleIntegerProperty idc = c.idc;
String query = "DELETE FROM customers WHERE customers.idc = " + idc;
当在字符串连接中使用对象
(不是字符串
)时,它会通过调用自动转换为
就可以了。 字符串
>toString()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();
}
关于mysql - Java FXML - NetBeans - 从表中删除 - MySQL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59681767/