我必须更新分布在 4 个 Mysql 表中的客户信息。我创建了 1 个客户类。当我第一次添加信息时,它被添加到填充表的可观察列表中,并且通过单击选定的行,信息将显示在文本框中进行编辑,但更新不会保存到 MySQL 表中。你能判断它是来自这部分代码还是来自程序的其他地方吗?我的代码有什么问题?
public void updateCustomer(Customer selectedCustomer, String user, LocalDateTime timePoint) throws Exception{
String query = "UPDATE customer, address, city, country"
+ " SET customer.customerName = '"+selectedCustomer.getCustomerName()+"', customer.lastUpdate = '" +timePoint+"', customer.lastUpdateBy = '"+user+ "', "
+ " address.address = '" +selectedCustomer.getAddress()+ "', address.address2 = '" +selectedCustomer.getAddress2()+ "', address.postalCode = '" +selectedCustomer.getPostalCode()+ "', address.phone = '" +selectedCustomer.getPhone()+ "', address.lastUpdate='" +timePoint+ "', address.lastUpdateBy = '" +user+ "', "
+ " city.city = '"+selectedCustomer.getCity()+"',city.lastUpdate='"+timePoint+"',city.lastUpdateBy = '"+user+ "', "
+ " country.country = '"+selectedCustomer.getCountry()+"',country.lastUpdate ='"+timePoint+"',country.lastUpdateBy = '"+user+ "' "
+ " WHERE customer.customerId = " +selectedCustomer.getCustomerId()+ " AND customer.addressId = address.addressId AND address.cityId = city.cityId AND city.countryId = country.countryId " ;
statement.executeUpdate(query);
}
最佳答案
我通常做的是:
- 创建我的数据类。
- 在我的数据库类上创建加载和保存方法。
- 设置 FXML,以便 TableColumns 显示数据类中的正确信息
- 将数据从数据库获取到 ObservableList(我喜欢使用 Derby,但这应该没有什么区别)并将其放入表中。
- 向选择模型添加一个监听器,以便当表中的所选项目发生更改时,所选项目将由另一个变量(例如“selectedCustomer”)引用,并且该变量的数据将显示在可编辑文本字段或组合框或其他内容中。在文本框中显示 selectedCustomer 时,我不使用绑定(bind)。我只使用普通的 setTexts。
- 当用户点击“保存”或其他操作时,文本字段中的数据将设置到 selectedCustomer 中(例如,
selectedCustomer.setName(nameText.getText());
) - 我调用数据库类的 save 方法(例如,
DB.save(selectedCustomer);
) - 这应该可以解决问题!从来没有让我失望过。
但是,我可能有错,因为我懒得去读你的 SQL 语句。看在上帝的份上,请学习使用PreparedStatements!首先,我不太明白你的 table 是如何设置的,所以我无法发表评论,但这确实很难理解。但是,如果我大胆猜测,我认为问题可能与这部分有关:
WHERE ... AND customer.addressId = address.addressId AND address.cityId = city.cityId AND city.countryId = country.countryId
我不明白该部分是如何工作的——要么该 SQL 语句没有意义,要么我的 SQL 需要练习(可能是后者)。
既然您使用 MySQL,那么您是否可以使用管理器(例如 PHPMyAdmin 或由于您使用 Java、SQuirreL)来尝试手动执行 SQL 语句,看看会发生什么?如果您输入 SQL 语句但没有发生任何变化(本应发生变化),那么您的 SQL 语句就有问题。
关于mysql - 使用javafx和Mysql进行多表更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49419815/