如何在 JDBC 中将 Date 值转换为字符串?

jdbcjava 8object oriented programmingprogramming

java.sql.Date 类的 toString() 方法返回当前 date 对象所表示的日期的转义格式:yyyy-mm-dd。使用此方法可以将 Date 对象转换为字符串。

Date date = rs.getDate("Dispatch_Date");
date.toString());

假设我们有一个名为 dispatch_data 的表,其中包含 3 条记录,如下所示:

+--------------+------------------+---------------+----------------+
| Product_Name | Name_Of_Customer | Dispatch_Date | Location       |
+--------------+------------------+---------------+----------------+
| KeyBoard     | Amith            | 1981-12-05    | Hyderabad      |
| Ear phones   | Sumith           | 1981-04-22    | Vishakhapatnam |
| Mouse        | Sudha            | 1988-11-05    | Vijayawada     |
+--------------+------------------+---------------+----------------+

以下 JDBC 程序与数据库建立连接,检索 dispatch_data 表的内容,使用 toString() 方法将日期对象转换为字符串值,并将表的内容与日期值(转换为字符串格式)一起显示:

import java.sql.Connection;
import java.sql.Date;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class DateToString {
   public static void main(String args[])throws Exception {
      //注册驱动程序
      DriverManager.registerDriver(new com.mysql.jdbc.Driver());
      //获取连接
      String mysqlUrl = "jdbc:mysql://localhost/mydatabase";
      Connection con = DriverManager.getConnection(mysqlUrl, "root", "password");
      System.out.println("Connection established......");
      //创建 Statement 对象
      Statement stmt = con.createStatement();
      //创建 Statement 对象
      stmt = con.createStatement();
      ResultSet rs = stmt.executeQuery("select * from dispatch_data");
      //检索值
      while(rs.next()) {
         System.out.println("Product Name: "+rs.getString("Product_Name"));
         System.out.println("Name Of The Customer: "+rs.getString("Name_Of_Customer"));
         //检索日期
         Date date = rs.getDate("Dispatch_Date");
         //将 Date 对象转换为字符串
         System.out.println("Date: "+date.toString());
         System.out.println();
      }
   }
}

输出

Connection established......
Product Name: KeyBoard
Name Of The Customer: Amith
Date: 1981-12-05

Product Name: Ear phones
Name Of The Customer: Sumith
Date: 1981-04-22

Product Name: Mouse
Name Of The Customer: Sudha
Date: 1988-11-05

相关文章