RowSet 可以滚动吗?请举例说明。

jdbcjava 8object oriented programmingprogramming

RowSet 对象与 ResultSet 类似,除了 ResultSet 的功能外,它还存储表格数据。RowSet 遵循 JavaBeans 组件模型。

默认情况下,如果检索 ResultSet 对象,其游标只会向前移动。也就是说,您可以从头到尾检索其内容。

但是,在可滚动的结果集中,游标可以向前和向后滚动,并且您也可以向后检索数据。

要使 ResultSet 对象可滚动,您需要创建一个,如下所示 −

Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);

然而,RowSet 对象默认是可滚动的。因此,当底层数据库没有提供可滚动的 ResultSet 对象时,您可以使用 RowSet 代替。

示例

假设数据库中有一个名为 Dispatches 的表,其中包含 5 条记录,如下所示 −

+-------------+--------------+--------------+--------------+-------+----------------+
| ProductName | CustomerName | DispatchDate | DeliveryTime | Price | Location       |
+-------------+--------------+--------------+--------------+-------+----------------+ 
| Key-Board   | Raja         | 2019-09-01   | 05:30:00     | 7000  | Hyderabad      |
| Earphones   | Roja         | 2019-05-01   | 05:30:00     | 2000  | Vishakhapatnam |
| Mouse       | Puja         | 2019-03-01   | 05:29:59     | 3000  | Vijayawada     |
| Mobile      | Vanaja       | 2019-03-01   | 04:40:52     | 9000  | Chennai        |
| Headset     | Jalaja       | 2019-04-06   | 18:38:59     | 6000  | Goa            |
+-------------+--------------+--------------+--------------+-------+----------------+

以下 JDBC 程序从后往前检索 RowSet 的内容

import java.sql.DriverManager;
import javax.sql.RowSet;
import javax.sql.rowset.RowSetProvider;
public class ScrolableUpdatableRowSet {
   public static void main(String args[]) throws Exception {
      //注册驱动程序
      DriverManager.registerDriver(new com.mysql.jdbc.Driver());
      //创建 RowSet 对象
      RowSet rowSet = RowSetProvider.newFactory().createJdbcRowSet();
      //设置 URL
      String mysqlUrl = "jdbc:mysql://localhost/SampleDB";
      rowSet.setUrl(mysqlUrl);
      //设置用户名
      rowSet.setUsername("root");
      //设置密码
      rowSet.setPassword("password");
      //设置查询/命令
      rowSet.setCommand("select * from Dispatches");
      rowSet.setCommand("SELECT ProductName, CustomerName, Price, Location from Dispatches where price > ?");
      rowSet.setInt(1, 2000);
      rowSet.execute();
      rowSet.afterLast();
      while(rowSet.previous()) {
         System.out.print("Product Name: "+rowSet.getString("ProductName")+", ");
         System.out.print("Customer Name: "+rowSet.getString("CustomerName")+", ");
         System.out.print("Price: "+rowSet.getString("Price")+", ");
         System.out.print("Location: "+rowSet.getString("Location"));
         System.out.println("");
      }
   }
}

输出

Product Name: Headset, Customer Name: Jalaja, Price: 6000, Location: Vijayawada
Product Name: Mobile, Customer Name: Vanaja, Price: 9000, Location: Vijayawada
Product Name: Mouse, Customer Name: Puja, Price: 3000, Location: Vijayawada
Product Name: Key-Board, Customer Name: Raja, Price: 7000, Location: Hyderabad

相关文章