【发布时间】:2020-02-01 14:07:53
【问题描述】:
我正在开发一个使用 FX 和 SQL 的 Java 项目。在这个 Java 项目中,我有一个商店,我可以在其中将产品添加到数据库中。
现在我还希望我可以更新产品。我只能更新产品的价格,而不能更新品牌名称和类型名称。当我想更新品牌名称或类型名称时,我在控制台中收到错误消息。
这是更新产品的代码:
public int editProduct(Double price, int brand, int type, int id) {
String sql = "UPDATE products SET price=?, id_brand=?, id_type=? WHERE id=?";
try {
Class.forName(DRIVER);
Connection con = DriverManager.getConnection(DB_URL, USER, PASS);
PreparedStatement stmt = con.prepareStatement(sql);
stmt.setDouble(1, price);
stmt.setInt(2, brand);
stmt.setInt(3, type);
stmt.setInt(4, id);
int rows = stmt.executeUpdate();
getProducts();
con.close();
return rows;
} catch (ClassNotFoundException | SQLException ex) {
System.out.println("SQL error updaten product");
System.out.println(ex.getMessage());
}
return -1;
}
-
public class EditProductController {
@FXML TextField productId, productBrand, productType, productPrice;
@FXML Label berichtMelding;
@FXML Button saveButton;
private StoreDataAccesObject storeDDA;
public void fill (Product data) {
berichtMelding.setText(Integer.toString(data.getId()));
productType.setText(data.getType());
productBrand.setText(data.getBrand());
productPrice.setText(Double.toString(data.getPrice()));
}
public void updateProductButton() {
storeDDA = new StoreDataAccesObject("noorderpoort", "toets");
ArrayList<String> errorList = new ArrayList<>();
String brand = productBrand.getText();
String type = productType.getText();
String price = productPrice.getText();
String id = berichtMelding.getText();
int idBrand;
int idType;
if (brand.trim().length() <= 0 || type.trim().length() <= 0 || price.trim().length() <= 0) {
errorList.add("Alle velden moeten ingevuld zijn.");
} else {
if (storeDDA.nameExists("brands", brand) > 0) { //checking if brand exists in database.
idBrand = storeDDA.nameExists("brands", brand);
} else {
idBrand = storeDDA.nameExists("brands", brand);
if (idBrand < 0) {
errorList.add("Brand niet opgeslagen");
}
}
if (storeDDA.nameExists("types", type) > 0) {
idType = storeDDA.nameExists("types", type);
} else {
idType = storeDDA.nameExists("types", type);
if (idType < 0) {
errorList.add("Type niet opgeslagen");
}
}
if (storeDDA.editProduct(Double.parseDouble(price), idBrand, idType, Integer.parseInt(id)) <= 0) {
berichtMelding.setText("Product niet geupdate.");
} else {
Stage editProduct = (Stage) saveButton.getScene().getWindow();
editProduct.close();
}
}
if (!errorList.isEmpty()) {
String errorText = "";
for (String error : errorList) {
errorText += error;
}
berichtMelding.setText(errorText);
}
}
}
表格:
【问题讨论】:
-
描述你的表。
-
我添加了一张桌子的照片@nnn
-
你想在 id_brand 中传递什么值?
-
例如品牌叫“三星”,我想改成“LG”。然后,当我按下按钮将其更改为“LG”时出现该错误@NaveenArora
-
是的没错,而且问题不在于品牌名称,而在于 id_brand。可能是您正在尝试更新 id_brand 中的某些值。