使用javafx和Mysql更新多表

时间:2018-03-22 02:58:37

标签: mysql javafx updates

我必须更新分布在4个Mysql表中的客户信息。我创建了1个Customer类。当我第一次添加信息时,它会被添加到填充表的可观察列表中,通过单击选定的行,信息将显示在文本框中进行编辑,但更新不会保存到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);

}

1 个答案:

答案 0 :(得分:0)

我通常做的是:

  1. 创建我的数据类。
  2. 在我的数据库类上创建加载和保存方法。
  3. 设置FXML,以便TableColumns显示来自数据类的正确信息
  4. 将数据从数据库中获取到ObservableList中(我喜欢使用Derby,但这不应该有所作为)并将其放入表中。
  5. 向选择模型添加一个监听器,以便当表中的选定项发生更改时,所选项将被另一个变量引用(例如" selectedCustomer"并且该变量的数据显示为可编辑的文本字段或组合框或其他。请注意,在文本框中显示selectedCustomer时我不会使用绑定。我只使用普通的setTexts。
  6. 当用户点击“保存”或其他内容时,文本字段中的数据将设置为selectedCustomer(例如,selectedCustomer.setName(nameText.getText());
  7. 我称之为数据库类'保存方法(例如,DB.save(selectedCustomer);
  8. 应该这样做!我从未失败过。
  9. 但是,我可能在这里有错,因为我无法阅读您的SQL语句。为了善良,请学习使用PreparedStatements!首先,我不太了解你的桌子是如何设置的,所以我无法发表评论,但这真的很难理解。但是,如果我采取疯狂的猜测,我认为问题可能与此部分有关:

    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语句就会出错。