首页 > 代码库 > 为什么要使用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的连接都已经关闭了,而且仍然可以进行数据循环出值来。使用方法也很简单(红色字体所示)
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。