如何在JDBC中将Date值转换为字符串?
toString()
java.sql.Date类的方法返回转义格式:当前日期对象表示的日期的yyyy-mm-dd。使用此方法,可以将Date对象转换为String。
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()
方法将日期对象转换为String值,并显示表的内容以及Date值(将其转换为String格式):
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对象转换为String-
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
以上是 如何在JDBC中将Date值转换为字符串? 的全部内容, 来源链接: utcz.com/z/326994.html