甲行集对象类似于结果集,它也存储表格数据中,除了一个结果的特征。RowSet遵循JavaBeans组件模型。
如果默认情况下检索ResultSet对象,则其光标仅向前移动。即,您可以从头到尾检索它的内容。
但是,在可滚动的结果集中,光标可以前后滚动,您也可以向后检索数据。
要使ResultSet对象可滚动,您需要创建一个对象,如下所示-
Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
而RowSet对象默认是可滚动的。因此,只要基础数据库不提供Scrollable 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