且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-12-03 18:58:58

谢谢@Germann ......

Thank you @Germann ...

我解决了,我会提供解决方案,以便其他人可以从中获得帮助。

I solved it, and I will provide the solution so that others can get help from it.

你是对的 resultSet.absolute(...); 返回布尔值,但它也将光标移动到其参数 resultSet.absolute(table。 getSelectedRow()); 。那么问题是什么。

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.

问题是:
dTableModel.removeRow(table.getSelectedRow()); 之前不能调用 resultSet.absolute(table.getSelectedRow()); 因为(第一个)它删除了所选行,因为它是删除后,第二个方法没有选中任何内容,因此 table.getSelectedRow()返回-1。并且如文档中所指定的, absolute(-1)将光标移动到最后一行,并删除基础数据库中的最后一行。

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.

因此解决方案是颠倒这些行的顺序,我更喜欢在 resultSet.deleteRow();

之后进行>

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