RowSet 是否可滚动?通过一个示例说明?
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 { //Registering the Driver DriverManager.registerDriver(new com.mysql.jdbc.Driver()); //Creating the RowSet object RowSet rowSet = RowSetProvider.newFactory().createJdbcRowSet(); //Setting the URL String mysqlUrl = "jdbc:mysql://127.0.0.1/SampleDB"; rowSet.setUrl(mysqlUrl); //Setting the user name rowSet.setUsername("root"); //Setting the password rowSet.setPassword("password"); //Setting the query/command 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
广告