1. 使用离线的RowSet可以使得不用一直保持Connection链接,离线RowSet会直接将地城数据读入到内存,封装成RowSet对象,而RowSet对象可以直接当作Java  Bean来使用
  2. CachedRowSet是所有离线RowSet的父接口
  3. 程序运行前和程序运行后对数据库进行查询的结果如下java数据库编程(10) 离线RowSet
  4. import javax.sql.rowset.CachedRowSet;
    import javax.sql.rowset.RowSetFactory;
    import javax.sql.rowset.RowSetProvider;
    import java.io.FileInputStream;
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.ResultSet;
    import java.sql.Statement;
    import java.util.Properties;
    
    public class CachedRowSetTest {
    //    常规操作,不解释~~
        private static String driver;
        private static String url;
        private static String user;
        private static String pass;
    
        public void initParam(String fileName) throws Exception{
            Properties prop =  new Properties();
            prop.load(new FileInputStream(fileName));
            driver = prop.getProperty("driver");
            url  = prop.getProperty("url");
            user = prop.getProperty("user");
            pass = prop.getProperty("pass");
        }
    
        public CachedRowSet query(String sql) throws  Exception{
            Class.forName(driver);
            Connection conn = DriverManager.getConnection(url, user, pass);
            Statement stmtm = conn.createStatement();
            ResultSet rs = stmtm.executeQuery(sql);
    
            RowSetFactory factory = RowSetProvider.newFactory();
    //        创建RowSetFactory对象
    
            CachedRowSet cachedRowSet = factory.createCachedRowSet();
    //        通过RowSetFactory对象创捷CacheRowSet对象
    
            cachedRowSet.populate(rs);
    //        将查询的结果集封装到CachedRowSet中
    
    //        关闭连接
            rs.close();
            stmtm.close();
            conn.close();
    
            return cachedRowSet;
    //        将封装有结果集的CachedRowSet返回
        }
        public static void main(String args[]) throws  Exception{
            CachedRowSetTest ct = new CachedRowSetTest();
            ct.initParam("mysql.ini");
            CachedRowSet rs = ct.query("select * from students");
            rs.afterLast();
    
    //        对离线RowSet进行一些处理
            while (rs.previous()){
                System.out.println(rs.getString(1) + "\t" + rs.getString(2));
    
                if(rs.getString("Sname").equals("Smith")){
                    rs.updateString("Sno", "S4");
                    rs.updateRow();
                }
            }
    //        重新打开数据库链接,并且将修改过的结果集同步到数据库中
            Connection conn = DriverManager.getConnection(url,user,pass);
            conn.setAutoCommit(false);
            rs.acceptChanges(conn);
        }
    }
    //运行程序,看到以下输出结果
    //        S3	Tom
    //        S2	Marry
    //        S0	Smith

     

相关文章: