JDBC 中 Result 是什麼?如何從 ResultSet 物件中檢索資料?


JDBC 中的ResultSet 介面表示 SQL 查詢生成的關係型資料。該介面包含一個指向當前行的遊標。最初,此遊標指向第一行之前。

在結果集中移動指標

ResultSet 介面的next() 方法將當前(ResultSet)物件的指標從當前位置移動到下一行。此方法返回一個布林值,如果當前位置後面沒有行,則返回 false,否則返回 true。因此,在 while 迴圈中使用此方法可以遍歷結果集的內容。

while(rs.next()){
}

獲取每個記錄的列值

ResultSet 介面(還)提供 getter 方法 (getXXX()) 以檢索行中各列的值。每個 getter 方法都有兩個變體

  • getXXX(int columnIndex): 接受一個整數值,表示列的索引,並返回其值。

  • getXXX(String columnLabel ): 接受一個字串值,表示列的名稱,並返回其值。

您需要根據表中列的資料型別使用相應的 getter 方法。

示例

假設我們有一個名為 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 |
+--------------+-----------+

示例

以下示例檢索了Dataset 表中的所有記錄並列印結果

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class RetrievingData {
   public static void main(String args[]) throws Exception {
      //Registering the Driver
      DriverManager.registerDriver(new com.mysql.jdbc.Driver());
      //Getting the connection
      String mysqlUrl = "jdbc:mysql:///TestDB";
      Connection con = DriverManager.getConnection(mysqlUrl, "root", "password");
      System.out.println("Connection established......");

      //Creating a Statement object
      Statement stmt = con.createStatement();
      //Retrieving the data
      ResultSet rs = stmt.executeQuery("select * from Dataset");

      System.out.println("Contents of the table");
      while(rs.next()) {
         System.out.print("Brand: "+rs.getString("Mobile_Brand")+", ");
         System.out.print("Sale: "+rs.getString("Unit_Sale"));
         System.out.println("");
      }
   }
}

輸出

Connection established......
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

更新於:2020 年 3 月 9 日

2K+ 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

開始吧
廣告