技术文章和资源

技术文章(时间排序)

热门类别

Python PHP MySQL JDBC Linux

如何使用 JDBC 程序检索表的特定列?

jdbcjava 8mysqlmysqli database

JDBC 中的 ResultSet 接口表示由 SQL 查询生成的表格数据。它有一个指向当前行的游标。最初,此游标位于第一行之前。

您可以使用 next() 方法移动游标,并且可以使用 ResultSet 接口的 getter 方法(getInt()、getString()、getDate() 等)检索行的列值。

要从表中检索所需数据:

  • 连接到数据库。

  • 创建 Statement 对象。

  • 使用 executeQuery() 方法执行 Statement。向此方法传递字符串格式的选择查询。要检索所有值,我们使用以下查询:

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

相关文章