我的javaFx应用程序有许多带有可编辑表格单元格的表格,用于填充sql数据库中的数据。我还想在通过表格单元格进行数据编辑后对数据库进行更改。根据这个toturial“https://docs.oracle.com/javafx/2/ui_controls/table-view.htm” 我使用以下代码创建了可编辑表格单元格。
item_price_col.setCellValueFactory(
new PropertyValueFactory("price")
);
item_price_col.setCellFactory(TextFieldTableCell.forTableColumn());
item_price_col.setOnEditCommit(
new EventHandler<CellEditEvent<Item, String>>() {
@Override
public void handle(CellEditEvent<Item,String> t) {
String old_price=t.getOldValue();
((Item) t.getTableView().getItems().get(
t.getTablePosition().getRow())
).setPrice(t.getNewValue());
String new_price=t.getNewValue();
System.out.println("Old Price:"+old_price);
System.out.println("New Price:"+new_price);
}
}
);
但是编辑后它不会对数据库进行任何更改。因此,我认为必须在该句柄方法内编写更新查询。但我只能知道旧值和新值。我无法做出像“更新商品集价格=新价格,其中价格=旧价格”这样的查询语句。如果我将商品的单个价格更新为新值,则商品表中的每个商品与我编辑的商品具有相同的价格将会改变新的价格值。有什么办法可以解决这个问题吗? 这是我的项目表结构。
item | CREATE TABLE `item` (
`code` int(11) NOT NULL,
`name` varchar(50) DEFAULT NULL,
`price` varchar(50) NOT NULL,
`whole_sale_price` varchar(50) NOT NULL,
`orginal_price` varchar(50) DEFAULT NULL,
PRIMARY KEY (`code`),
UNIQUE KEY `code` (`code`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 |
最佳答案
为您的商品保留数据库中给出的 id
字段。
如果数据库中没有主键或唯一键,则可能会犯一些架构错误。无论如何,在某些数据库服务器中指定了行 ID。
private int id; // id field for item object.
更新时包含 id 作为条件。
update sometable set price = item.getPrice() where id = item.getId();
我知道sql写得不好,但我希望你能明白
并且您不必在表格网格中显示 id 字段的值。
大多数系统都使用这种技术
2015年12月18日编辑
表中有代码列。通过 jdbc 检索到您的项目对象的 id 字段中。
有一个例子
关于java - 通过JavaFx表格单元格编辑动态更改SQL数据库的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34339901/