如何在JDBC中从表中检索日期?


ResultSet 接口提供了一个名为 getDate() 的方法,此方法接受一个整型参数,表示需要从中检索日期值的列的索引(或表示列名称的字符串参数)。要从表中检索日期值,请执行以下操作:

  • 使用DriverManager类的registerDriver()方法注册驱动程序类。将驱动程序类名作为参数传递给它。

  • 使用DriverManager类的getConnection()方法连接到数据库。将URL(字符串)、用户名(字符串)、密码(字符串)作为参数传递给它。

  • 使用Connection接口的createStatement()方法创建一个Statement对象。

  • 使用executeQuery()方法执行查询。将检索数据的select查询(字符串)作为参数传递给它。

  • 从获得的结果集对象中,使用ResultSet接口的getDate()方法获取日期值(以及其他值)。将列名(字符串)作为参数传递给它。

示例

假设数据库中有一个名为Emp的表,如下所示:

+--------+------------+----------------+
| Name   | DOB        | Location       |
+--------+------------+----------------+
| Amit   | 1989-09-26 | Hyderabad      |
| Sumith | 1989-09-01 | Vishakhapatnam |
| Sudha  | 1980-09-01 | Vijayawada     |
+--------+------------+----------------+

以下是一个JDBC示例,它使用ResultSet接口的getDate()和getString()方法从表中检索日期和字符串值。

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class RetrievingDate {
   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 Statement object
      Statement stmt = con.createStatement();
      ResultSet rs = stmt.executeQuery("select * from Emp");
      //Retrieving values
      while(rs.next()) {
         System.out.print("Name: "+rs.getString("Name"));
         System.out.print(" Date of Birth: "+rs.getDate("DOB"));
         System.out.print(" Location: "+rs.getString("Location"));
         System.out.println();
      }
   }
}

输出

Connection established......
Name: Amit Date Of Birth: 1989-09-26 Location: Hyderabad
Name: Sumith Date Of Birth: 1989-09-01 Location: Vishakhapatnam
Name: Sudha Date Of Birth: 1980-09-01 Location: Vijayawada

更新于:2019年7月30日

4K+ 次浏览

启动您的职业生涯

完成课程获得认证

开始学习
广告
© . All rights reserved.