如何使用 JDBC 程式檢索表的特定列?


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

您可以使用 **next()** 方法移動遊標,並且可以使用 ResultSet 介面的 getter 方法(getInt()、getString()、getDate() 等)檢索行的列值。

要從表中檢索所需資料

  • 連線到資料庫。

  • 建立一個 Statement 物件。

  • 使用 **executeQuery()** 方法執行 Statement。為此方法傳遞字串格式的 select 查詢。要檢索所有值,我們使用以下查詢

Select * from TableName;
  • 要檢索特定列,請將所需的列名指定為 *,例如

select Name, DOB from Emp

示例

假設我們在資料庫中有一個名為 Emp 的表,其描述如下

+----------+--------------+------+-----+---------+-------+
| Field    | Type         | Null | Key | Default | Extra |
+----------+--------------+------+-----+---------+-------+
| Name     | varchar(255) | YES  |     | NULL    |       |
| DOB      | date         | YES  |     | NULL    |       | 
| Location | varchar(255) | YES  |     | NULL    |       |
+----------+--------------+------+-----+---------+-------+

以下 JDBC 示例從 Emp 表中檢索員工的姓名和出生日期值。

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class RetrievingParticularColumn {
      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:///sampleDB";
      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 Name, DOB from Emp");

      System.out.println("Contents of the table");
      while(rs.next()) {
         System.out.print("Name of the Employee: "+rs.getString("Name")+", ");
         System.out.print("Date of Birth: "+rs.getDate("DOB"));
         System.out.println("");
      }
   }
}

輸出

Connection established......
Contents of the table
Name of the Employee: Amit, Date of Birth: 1970-01-08
Name of the Employee: Sumith, Date of Birth: 1970-01-08
Name of the Employee: Sudha, Date of Birth: 1970-01-05

更新於: 2019-07-30

5K+ 瀏覽量

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告