如何使用 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+ 浏览量

开启你的 职业生涯

通过完成课程获得认证

开始学习
广告

© . All rights reserved.