什么是RowSet?如何使用RowSet检索表的内容?请解释。
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 {
//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:///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();
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
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP