java getselectedrow,Java:删除选定的行ResultSet,从数据库中删除最后一行?

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();

}

}

});

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值