when I select a row and press the "remove" button:
In the swing interface the selected row is removed (as expected). But
In the actual database the last row is deleted whatever the selected row was (not expected).
The deleted row is always the last row in the database, whatever the actual selected row was. There are no errors and no exceptions thrown in my code. it works without any interruptions.
I actually added the necessary things to my code:
Statement sqlStatement = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
and Add a "remove" button to delete a selected row:
JButton removeEmployee = new JButton("Remove Selected");
removeEmployee.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
dTableModel.removeRow(table.getSelectedRow());
try
{
resultSet.absolute(table.getSelectedRow());
resultSet.deleteRow();
} catch (SQLException e1)
{
e1.printStackTrace();
}
}
});
Thank you @Germann ...
I solved it, and I will provide the solution so that others can get help from it.
You are right that resultSet.absolute(...);
returns boolean value, but it also moves the cursor to the specified row in its argument resultSet.absolute(table.getSelectedRow());
. So what was the problem.
The problem is:
The line dTableModel.removeRow(table.getSelectedRow());
mustn't be called before resultSet.absolute(table.getSelectedRow());
because (the first) it removes the selected row, and because it is removed, the second method gets nothing selected, so table.getSelectedRow()
returns -1. and as specified in the documentation, absolute(-1)
moves the cursor to the last line, and that deletes the last row in the underlying database.
So the solution is to reverse the order of those lines, and I prefer to make it after resultSet.deleteRow();
JButton removeEmployee = new JButton("Remove Selected");
removeEmployee.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
try
{/* here I added +1 because it moves the row to the selected row -1
I don't know why. But it now works well */
resultSet.absolute(table.getSelectedRow()+1);
resultSet.deleteRow();
dTableModel.removeRow(table.getSelectedRow());
} catch (SQLException e1)
{
e1.printStackTrace();
}
}
});
removePres.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
// Will remove which ever row that is selected
try {
// Moves the database to the row currently selected
// getSelectedRow returns the row number for the selected
resultSet.absolute(table.getSelectedRow()+1);
resultSet.deleteRow();
dTableModel.removeRow(table.getSelectedRow());
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
shows error in resultset??