当我选择通过ID值将其删除的数据时,我想直接从GUI中直接从TableView中删除数据,它显示错误,提示我强制转换为键入 StudentData 或同时创建一个ObservableList他们中的不起作用。我在做什么错了?
public void Delete(ActionEvent event)
{
try
{
Connection conn = SqliteConnection.Connector();
StudentData data = (StudentData) studenttable.getSelectionModel().getSelectedItems();
PreparedStatement ps = conn.prepareStatement("DELETE FROM Studentlist WHERE ID =?;");
ps.setString(1, data.getID());
ps.executeUpdate();
}
catch (SQLException e) {
e.printStackTrace();
}
}
我尝试了上面的代码,但是仍然没有结果不能删除我从GUI中选择的行
答案 0 :(得分:0)
假设ID
列为数字类型,例如整数,则应将数字Java类型绑定到?
占位符,例如
Connection conn = SqliteConnection.Connector();
StudentData data = (StudentData) studenttable.getSelectionModel().getSelectedItems();
PreparedStatement ps = conn.prepareStatement("DELETE FROM Studentlist WHERE ID = ?");
ps.setInt(1, data.getID());
ps.executeUpdate();
如果data.getID()
返回String
,则使用以下方法将其解析为整数:
int theID = Integer.valueOf(data.getID());
,然后将其绑定到您的语句:
ps.setInt(1, theID);
请注意,从JDBC进行调用时,无需在delete语句的末尾添加分号。
答案 1 :(得分:0)
public void Delete(ActionEvent event)
{
try
{
Connection conn = SqliteConnection.Connector();
PreparedStatement ps = conn.prepareStatement("DELETE FROM Studentlist WHERE ID = ?");
StudentData studentdata = studenttable.getSelectionModel().getSelectedItem();
ps.setString(1, studentdata.getID());
ps.execute();
conn.close();
}
catch (SQLException e)
{
System.out.println(e);
}
}
我的猜测是
您的数据模型类名称为 StudentData
您的TableView名称为可学习
所以...语法是...
//to select tableview row
StudentData selectedrow = studenttable.getSelectionModel().getSelectedItem();
//prepare query with blank ID to be filled with the value of the selected row
PreparedStatement ps = conn.prepareStatement("DELETE FROM Studentlist WHERE ID = ?");
//from the selected row getID only
ps.setString(1, selectedrow.getID());
//execute delete operation e.g DELETE FROM Studentlist WHERE ID = 123
ps.execute();
请注意,TableView必须将StudentData作为类型参数,以避免强制转换:
@FXML
private TableView<StudentData> studenttable;