什麼是 RowSet 物件,使用 JDBC 程式進行解釋?
RowSet 是對 ResultSet 物件的包裝。它可以連線或從資料庫斷開連線,並且可以序列化。它透過設定屬性來維護一個 JavaBean 元件。您可以在網路上傳遞 RowSet 物件。預設情況下,RowSet 物件是可滾動的可更新的,它用於讓 ResultSet 物件可滾動和可更新。
您可以使用
RowSetProvider.newFactory().createJdbcRowSet() 方法獲取 RowSet。
示例
假設我們在資料庫中有一個名為 dataset 的表,如下所示
+--------------+-----------+ | 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 { //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:///TestDB"; rowSet.setUrl(mysqlUrl); //Setting the user name rowSet.setUsername("root"); //Setting the password rowSet.setPassword("password"); //Setting the query/command 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
廣告