RowSet对象类似于ResultSet,它还存储表格数据,除了ResultSet的功能外,RowSet遵循JavaBeans组件模型。它可以在可视Bean开发环境中用作JavaBeans组件,即在类似IDE的环境中,您可以可视地操纵这些属性。
RowSet接口提供了设置Java Bean属性以将其连接到所需数据库的方法-
无效的setURL(String url):
setUserName(String user_name)无效:
无效的setPassword(字符串密码):
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