首頁  >  文章  >  資料庫  >  JDBC 中的結果是什麼?如何從 ResultSet 物件檢索資料?

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

PHPz
PHPz轉載
2023-08-26 16:17:181402瀏覽

JDBC 中的ResultSet 介面表示 SQL 查詢產生的表格資料。它有一個指向當前行的遊標。最初,此遊標位於第一行之前。

JDBC 中的结果是什么?如何从 ResultSet 对象中检索数据?

在整個結果集中移動指標

#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://localhost/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

以上是JDBC 中的結果是什麼?如何從 ResultSet 物件檢索資料?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:tutorialspoint.com。如有侵權,請聯絡admin@php.cn刪除