【问题标题】:Logical error when trying to remove an item from a JList尝试从 JList 中删除项目时出现逻辑错误
【发布时间】:2014-01-15 05:26:44
【问题描述】:

我有一个 JList,它显示了我添加到数据库中的所有项目。当我想删除多个项目时,比如两个项目,只有其中一个被删除。这是我的代码: 这个方法来自我的 DAL 类:

public void removeStudent(Student student)throws SQLException{
  PreparedStatement studentStatement = getConnected().prepareStatement(
    "delete from student where spnr = ? and sname = ? and sadress = ? " +
     " and stel = ? ");

  studentStatement.setString(1, student.getIdNumber());
  studentStatement.setString(2, student.getName());
  studentStatement.setString(3, student.getAddress());
  studentStatement.setString(4, student.getTel());
  studentStatement.executeUpdate();
}

类控制器:

public void removeStudent(Student student) throws SQLException{
  dal.removeStudent(student);
}

和类视图。单击按钮删除时在 actionListener 中使用。

private void removeStudent(){
  try{
    controller.getDal().getStudentData().getName();
    controller.getDal().getStudentData().getAddress();
    controller.getDal().getStudentData().getIdNumber();   
    controller.getDal().getStudentData().getTel();

    controller.removeStudent(controller.getDal().getStudentData());
  }catch(Exception e){
    e.printStackTrace();
  }
}

还有 ActionEvent

if(infLst.getSelectedIndex() > -1){
  int choice = JOptionPane.showConfirmDialog(null, 
                 "Delete?" + "The student will be permamently deleted",
                 null,
                 JOptionPane.YES_NO_OPTION);
  if(choice == JOptionPane.YES_OPTION){
    //Removes from the JList            
    ((DefaultListModel)infLst.getModel()).removeElementAt(index);
    //And database 
    removeStudent();
  }else{
    return;
  }
}else{
  JOptionPane.showMessageDialog(null, "Please make sure you have selected an item from the list");
}
}}});

请考虑我是数据库编程领域的新手。提前致谢。

【问题讨论】:

    标签: java mysql data-access-layer


    【解决方案1】:

    当我想删除多个项目时,比如两个项目,只删除其中一个。

    您的代码只有一个 if 条件来检查所选索引,因此它只会删除一项。

    如果要删除所有选定的值,则需要使用 JList 中的方法,该方法返回多个要删除的值。查看 API 以了解可用于此目的的其他 getSelected...() 方法。然后你需要创建一个循环来删除所有的值。

    返回对象而不是索引值的方法会更容易使用,因为您可以从模型中删除对象,而无需担心先删除较高的索引值。

    【讨论】:

    • 我使用单间隔选择。我真的不想选择三个要删除的项目。我想一次删除三个项目。示例:选择第 1 项 --> 删除,选择第 2 项 --> 删除等等。
    • 问题不在于列表。这两个项目都从列表中删除,问题是该项目仍然存在的数据库,即使我已从 JList 中删除它
    • @Eskipo,您的 SQL 语句有一个“where 子句”,因此只有符合该条件的记录才会被删除。由于您只从 JList 中删除一项,因此从数据库表中只删除一行也是有意义的。也就是说,每个学生都会有一个唯一的身份证号码。如果事实上您甚至不需要 where 语句中的所有其他数据来删除学生,那么 ID 号就足够了。
    • 好的,但是 SQL 语句应该看起来不同吗?也许从学生中删除*?这应该解决问题吗?
    • 问题是,当我在命令行中测试程序时,我可以从数据库中删除这两个项目。当我使用 JList 时会出现此问题。
    猜你喜欢
    • 1970-01-01
    • 2014-04-22
    • 1970-01-01
    • 2020-03-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-12
    • 2016-07-07
    相关资源
    最近更新 更多