首页 > 代码库 > 为什么要使用CachedRowSetImpl?

为什么要使用CachedRowSetImpl?

   很多情况我们使用ResultSet 就会因为这样那样的问题,rs被关闭或数据链接被关闭,导致ResultSet不能使用。其实这个问题我们可以用CachedRowSetImpl来解决。我的理解是这是一个结果的缓存类,保存在其中的数据不会随着数据库和ResultSet的连接的关闭而丢失,可以传递。

   使用方法如下:

 1 package com.ifly.myhome.test; 2 import java.sql.*; 3 import com.sun.rowset.CachedRowSetImpl; 4 public class test { 5     private static Connection con; 6     private static String user = "kh"; 7     private static String password = "kh"; 8     private static  String className = "com.mysql.jdbc.Driver"; 9     private static String url = "jdbc:mysql://localhost:3306/student";10     public static void main(String[] args) {11         try {12             Class.forName(className);13             con = DriverManager.getConnection(url, user, password);14             String sql="select * from student";15             PreparedStatement pstm=con.prepareStatement(sql);16             pstm.execute();17             ResultSet rs=pstm.getResultSet();18             CachedRowSetImpl rowset=new CachedRowSetImpl();19             rowset.populate(rs);20             rs.close();21             pstm.close();22             con.close();23             while (rowset.next()) {24                 System.out.println("id:"+rowset.getString("id"));25                  26             }27              28         } catch (Exception e) {29             // TODO Auto-generated catch block30             e.printStackTrace();31         }32     }

从上面的例子可以看出,数据库和ResultSet的连接都已经关闭了,而且仍然可以进行数据循环出值来。使用方法也很简单(红色字体所示)