阅读:7052回复:0
java的离线数据集(RowSet)
http://blog.csdn.net/q1063823095/article/details/51760019
如果在开发应用的时候没有使用任何持久层框架,而是直接使用jdbc 的api编程的话,大家最长使用的就是ResultSet接口进行数据的读取了,但是大家也会觉得很不方便,因为ResultSet是在线的数据集,在读 取数据的过程中不能断开数据库联接,只有读取数据完成后才能close掉相关对象。其实java也提供了离线的数据集,那就是RowSet接口以及相关的 子接口。而且sun在jdk里面提供一个默认的实现,而且象oracle这样比较大型的数据库驱动里面也提供自己的RowSet实现。下面以sun的默认 实现来说明离线数据的使用吧,数据库为sql Server 2000,连接的数据库为Northwind。 import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import javax.sql.RowSet; import com.sun.rowset.CachedRowSetImpl; public class RowSetDemo { public static RowSet query(Connection connection, String sql) throws SQLException { //使用sun的默认RowSet实现 CachedRowSetImpl rowset = new CachedRowSetImpl(); //查询没有任何变化 Statement statement = connection.createStatement(); ResultSet rs = statement.executeQuery(sql); //这里就是填充离线集 rowset.populate(rs); //都可以关闭了,爽吧 rs.close(); statement.close(); return rowset; } public static void main(String[] args) throws Exception { Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); String connectionUrl = "jdbc:sqlserver://127.0.0.1:1433;database=Northwind;user=sa;password=huhuiyu"; Connection connection = DriverManager.getConnection(connectionUrl); RowSet rs = query(connection, "select * from Customers order by CustomerID;"); //关闭连接也没有关系了。 connection.close(); //和ResultSet使用一样。 while (rs.next()) { System.out.print(rs.getString(1) + " : "); System.out.println(rs.getString("CompanyName")); } } } 运行上面的例子就会将Customers的前两列的数据显示出来。其实RowSet还可以完成分页的功能。请看下面的方法。 public static RowSet query(Connection connection, String sql, int pageSize, int pageNumber) throws SQLException { CachedRowSetImpl rowset = new CachedRowSetImpl(); //要是可以滚动的结果集 Statement statement = connection.createStatement( ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY); ResultSet rs = statement.executeQuery(sql); //设定分页大小 rowset.setPageSize(pageSize); //计算一下开始游标位置 int skip=(pageNumber - 1) * pageSize + 1; //可以填充了 rowset.populate(rs, skip); rs.close(); statement.close(); return rowset; } public static void main(String[] args) throws Exception { Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); String connectionUrl = "jdbc:sqlserver://127.0.0.1:1433;database=Northwind;user=sa;password=huhuiyu"; Connection connection = DriverManager.getConnection(connectionUrl); //分页查询 RowSet rs = query(connection, "select * from Customers order by CustomerID;",5,2); //关闭连接也没有关系了。 connection.close(); //和ResultSet使用一样。 while (rs.next()) { System.out.print(rs.getString(1) + " : "); System.out.println(rs.getString("CompanyName")); } } 如果你不使用持久层,那么使用离线数据集可以很好的解决分页和数据库连接的问题。暂时就说这么多,细节的演示有时间再说。希望这篇入门的教程能够帮助到你。 |
|
最新喜欢:![]()
|