什么是 RowSet?如何使用 RowSet 检索表格内容?请解释一下?
jdbcjava 8object oriented programmingprogramming更新于 2025/3/6 20:28:17
RowSet 对象与 ResultSet 类似,也存储表格数据。除了 ResultSet 的特性外,RowSet 还遵循 JavaBeans 组件模型。这可以在可视化 Bean 开发环境中用作 JavaBeans 组件,也就是说,在 IDE 等环境中,您可以可视化地操作这些属性。
将 RowSet 连接到数据库
RowSet 接口提供了设置 Java Bean 属性的方法,以便将其连接到所需的数据库 −
- void setURL(String url):
- void setUserName(String user_name):
- void setPassword(String password):
属性
RowSet 对象包含属性,每个属性都有 Setter 和 getter 方法。使用这些方法,您可以设置和获取命令属性的值。
为了设置和获取不同数据类型的值,RowSet 接口提供了各种 setter 和 getter 方法,例如 setInt()、getInt()、setFloat()、getFloat()、setTimestamp、getTimeStamp() 等……
通知
由于 RowSet 对象遵循 JavaBeans 事件模型。每当发生诸如光标/指针移动、行插入/删除/更新等事件时,RowSet 内容都会发生变化。所有已注册的组件(实现了 RowSetListener 方法的组件)都会收到通知。
示例
假设数据库中有一个名为 Dispatches 的表,其中包含 5 条记录,如下所示 −
+----+-------------+--------------+--------------+--------------+-------+----------------+ | ID | ProductName | CustomerName | DispatchDate | DeliveryTime | Price | Location | +----+-------------+--------------+--------------+--------------+-------+----------------+ | 1 | Key-Board | Raja | 2019-09-01 | 05:30:00 | 7000 | Hyderabad | | 2 | Earphones | Roja | 2019-05-01 | 05:30:00 | 2000 | Vishakhapatnam | | 3 | Mouse | Puja | 2019-03-01 | 05:29:59 | 3000 | Vijayawada | | 4 | Mobile | Vanaja | 2019-03-01 | 04:40:52 | 9000 | Chennai | | 5 | Headset | Jalaja | 2019-04-06 | 18:38:59 | 6000 | Goa | +----+-------------+--------------+--------------+--------------+-------+----------------+
以下 JDBC 程序检索价格大于 5000 的记录的产品名称、客户名称、交货地点,并显示结果。
import java.sql.DriverManager;
import javax.sql.RowSet;
import javax.sql.rowset.RowSetProvider;
public class RowSetExample {
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();
System.out.println("Contents of the table");
while(rowSet.next()) {
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: Key-Board, Customer Name: Raja, Price: 7000, Location: Hyderabad Product Name: Mouse, Customer Name: Puja, Price: 3000, Location: Vijayawada Product Name: Mobile, Customer Name: Vanaja, Price: 9000, Location: Vijayawada Product Name: Headset, Customer Name: Jalaja, Price: 6000, Location: Vijayawada

