java.util.Date子类:
- java.sql.Date(日期)
- java.sql.Time(时间)
- java.sql.Timestamp(时间戳,包括日期和时间)
PreparedStatement里,有一个设置时间的方法:
- public void setDate(int parameterIndex,Date x)throws SQLException
这里的Date为java.sql.Date。要想把java.util.Date变为 java.sql.Date只能通过将日期转换为long型数据,再用java.util.Data接收long数据。
将java.util.Date转为long类型:public long getTime();
将long类型转为java.sql.Date:public Date(long date);
父类无法直接转型为子类对象,要先向上转型再向下转型。
演示代码:
package com.dao.Test;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.util.Date;
public class Test2 {
private static final String DRIVER = "com.mysql.jdbc.Driver";
private static final String URL = "jdbc:mysql://localhost:3306/school";
private static final String USER = "root";
private static final String PASSWORD = "123456";
public static void main(String[] args) throws Exception {
Date birthday = new Date();
Class.forName(DRIVER);
Connection connection = DriverManager.getConnection(URL, USER, PASSWORD);
String sql = "update students set birthday = ? WHERE stu_no = 1004;";
PreparedStatement stmt = connection.prepareStatement(sql);
//stmt.setDate(1, (java.sql.Date) birthday);无法直接转型
stmt.setDate(1, new java.sql.Date(birthday.getTime()));
try {
int len = stmt.executeUpdate();
System.out.println(len);
connection.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}