ResultSet连续通过Statement赋值,会出现错误

时间:2022-03-10 03:21:10

  ResultSet连续通过Statement赋值,会出现错误

  错误提示:jdbc Operation not allowed after ResultSet closed

  

 1 public Task[] getTaskInfo(String a_id){
 2         Task[] task = null;
 3         Connection conn = null;
 4         Statement stmt = null;
 5         ResultSet rs1 = null;
 6         ResultSet rs2 = null;
 7         try{
 8             Class.forName("com.mysql.jdbc.Driver");
 9             conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/p_note","root","root");
10             stmt = conn.createStatement();
11             String sql = "select count(*) from tasks";
12             String sql2 = "select * from tasks" ;
13             rs1 = stmt.executeQuery(sql);
14             rs2 = stmt.executeQuery(sql2);
15             int count = 0;
16             while(rs1.next()){
17                 count = rs1.getInt(1);
18             }
19             task = new Task[count];
20             int i=0;
21             while(rs2.next()){
22                 task[i] = new Task();
23                 task[i].setA_id(a_id);
24                 task[i].setT_id(rs2.getString("t_id"));
25                 task[i].setExecuteTime("t_time");
26                 task[i].setExecuteSite(rs2.getString("t_site"));
27                 task[i].setItemName(rs2.getString("t_items"));
28                 task[i].setSetout(rs2.getString("t_setout"));
29                 task[i].setT_createTime(rs2.getString("t_createTime"));
30                 task[i].setT_stamp(rs2.getString("t_stamp"));
31                 task[i].setT_stick(rs2.getString("t_stick"));
32                 i++;
33             }
34             
35         }catch(Exception ex){
36             ex.printStackTrace();
37             
38         }finally{
39             try{
40                 if(conn != null){
41                     conn.close();
42                 }
43                 if(stmt != null){
44                     stmt.close();
45                 }
46                 if(rs1 != null){
47                     rs1.close();
48                 }
49                 if(rs2 != null){
50                     rs2.close();
51                 }
52             }catch(Exception ex){
53                 ex.printStackTrace();
54             }
55         }
56        
57         return task;
58     }

  红色标记部分会出现错误

  

  原因:数据库提供的方法中,当再次用相同的Statement对ResultSet赋值时,会有个判断 if(ReslutSet != null) {}.在这个方法里面,rs1会被关掉。所以就存在了以上的问题。jdbc Operation not allowed after ResultSet closed