JDBC中可以用以下三个类表示时间:
Date:只表示日期;
Time:只表示时间
Timestamp:表示一个精确的时间(日期+时间)
这三个类型都是java.util.Date 的子类;但存在java.sql包中;
三个类的例子如下
import java.sql.Time;
import java.sql.Timestamp;
import java.sql.Connection;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class JDBC_TIME {
public static void main(String[] args) throws SQLException {
insert();
testGetTime();
}
public static void insert() {
//插入一条记录包含三种时间
Date birth=new Date(System.currentTimeMillis());
Time t=new Time(System.currentTimeMillis());
Timestamp ts=new Timestamp(System.currentTimeMillis());
String sql="insert into user values(null,?,?,?)";
try(Connection conn=JdbcUtil.getConnection();
PreparedStatement ps=conn.prepareStatement(sql);){
ps.setDate(1, birth);
ps.setTime(2, t);
ps.setTimestamp(3, ts);//三种set可以相互兼容,只是数据有可能会出现问题
ps.execute();
}catch(Exception e) {
e.printStackTrace(); }
System.out.println("执行完毕");
}
public static void testGetTime() throws SQLException {
String sql="select * from user";
Connection conn = JdbcUtil.getConnection();
try (Statement ps = conn.createStatement();
ResultSet rs=ps.executeQuery(sql);) {
while(rs.next()) {
System.out.println(rs.getDate(4)+"\t"+rs.getTime(4)+"\t"+rs.getTimestamp(4)+"\r\n");
System.out.println(rs.getDate(2)+"\t"+rs.getTime(2)+"\t"+rs.getTimestamp(2)+"\r\n");
}
}
}
}
其中setDate();setTime();setTimestamp(); 三种set可以相互兼容但是数据可能会出现问题