mysql - 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);
}
}
我错过了什么?我尝试了很多可能的解决方案,没有任何效果。基本上,当用户单击表中的行然后单击“删除”按钮时,应从表和数据库中删除该行。
提前致谢。
解决方案
SimpleIntegerProperty idc = c.idc;
String query = "DELETE FROM customers WHERE customers.idc = " + idc;
当在字符串连接中使用Object
a (不是 a )时,它会通过调用它自动转换为 a 。的字符串表示不仅仅是它的值,这意味着您的查询最终看起来像:String
String
toString()
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();
}
推荐阅读
- python - 为什么我不能只更改一个 pandas 列中的值?
- ios - 如何从 SwiftUI 列表和领域中删除数据
- javascript - react-router-dom 中缺少交换机和路由器模块
- angular - 更改 mat-spinner-button 的按钮颜色
- c++ - 使用 gmock 模拟一个创建另一个类的实例的类
- javascript - 回文代码看起来不错,但我无法让它运行
- c - 如何在C中引用深度嵌套的函数指针数组?
- python - 如何在没有有序字典的字典中访问循环中的前一个键?
- vim - vim 中的当前行号未用相对行号突出显示
- node.js - 没有从后端 Nuxtjs Auth 获得响应