什麼是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