background image

 
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");