RowSet是ResultSet对象的包装。它可以连接,断开数据库连接并可以序列化。它通过设置属性来维护JavaBean组件。您可以通过网络传递RowSet对象。默认情况下,RowSet对象是可滚动和可更新的,并且用于使ResultSet对象可滚动和可更新。
您可以使用
RowSetProvider.newFactory()。createJdbcRowSet()方法。
假设我们在数据库中有一个名为数据集的表,如下所示:
+--------------+-----------+
| mobile_brand | unit_sale |
+--------------+-----------+
| Iphone | 3000 |
| Samsung | 4000 |
| Nokia | 5000 |
| Vivo | 1500 |
| Oppo | 900 |
| MI | 6400 |
| MotoG | 4360 |
| Lenovo | 4100 |
| RedMi | 4000 |
| MotoG | 4360 |
| OnePlus | 6334 |
+--------------+-----------+
下面的JDBC示例创建一个RowSet对象,使用该对象检索名为dataset的表的内容:
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/TestDB";
rowSet.setUrl(mysqlUrl);
//设置用户名
rowSet.setUsername("root");
//设置密码
rowSet.setPassword("password");
//设置查询/命令
rowSet.setCommand("select * from Dataset");
System.out.println("Contents of the table");
while(rowSet.next()) {
System.out.print("Brand: "+rowSet.getString(1)+", ");
System.out.print("Sale: "+rowSet.getString(2));
System.out.println("");
}
}
}
Contents of the table
Brand: Iphone, Sale: 3000
Brand: Samsung, Sale: 4000
Brand: Nokia, Sale: 5000
Brand: Vivo, Sale: 1500
Brand: Oppo, Sale: 900
Brand: MI, Sale: 6400
Brand: MotoG, Sale: 4360
Brand: Lenovo, Sale: 4100
Brand: RedMi, Sale: 4000
Brand: MotoG, Sale: 4360
Brand: OnePlus, Sale: 6334