为什么我在执行查询时收到“ResultSet关闭后不允许操作”?

时间:2014-12-13 18:34:41

标签: java mysql jdbc

String sql = "Select * from EmployeeAccount";

try {
   Class.forName("com.mysql.jdbc.Driver");    
   Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/AttendanceSystemTest","root","");   
   Statement stmt=con.createStatement();
   ResultSet rs=stmt.executeQuery(sql);

   String user=txtid.getText();

   String pwd=new String (password.getPassword());
   int loop=0;

   while(rs.next()) {
      String uname=rs.getString("Emp_ID");
      String password=rs.getString("Password");

      if ((user.equals(uname)) && (pwd.equals(password))) {
         String s1 = "insert into Attendance (Emp_ID,Date,Time_in) Values ('" + user + "', now(), curtime());";
         stmt.executeUpdate(s1);
         loop++;
      }
  }

  rs.close();

  if (loop==0) {
     JOptionPane.showMessageDialog(null, "Username and Password not in database!");
   }
}

catch (Exception e) {
    JOptionPane.showMessageDialog(null,e);
}

1 个答案:

答案 0 :(得分:1)

stmt.executeUpdate(s1);循环内调用while(rs.next())会关闭ResultSet,因此,下一次调用rs.next()会抛出异常。

您应该使用不同的Statement实例来执行该更新。

  

当生成它的Statement对象关闭,重新执行,或者用于从多个结果序列中检索下一个结果时,ResultSet对象会自动关闭。

Source