By
Moment Only
更新日期:
java中的时间类型和mysql中的时间类型
mysql创建表并插入数据
1 2 3 4 5 6 7 8 9 10
| CREATE TABLE `time_test` ( `id` int(11) NOT NULL AUTO_INCREMENT, `dt` datetime DEFAULT NULL, `d` date DEFAULT NULL, `t` time DEFAULT NULL, `ts` timestamp(3) NULL DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;
INSERT INTO `time_test` VALUES ('1', '2019-06-06 10:05:06', '2019-06-06', '03:03:55', '2019-07-19 15:29:37.999');
|
time_test表的查询结果
1 2
| id dt d t ts 1 2019-06-06 10:05:06 2019-06-06 03:03:55 2019-07-19 15:29:37.999
|
JDBC解析结果集
1 2 3 4 5 6 7 8 9 10
| while(res.next()){ System.out.println(new Date(res.getDate("d").getTime())); System.out.println(res.getTime("t")); System.out.println(new Date(res.getTimestamp("dt").getTime())); System.out.println(res.getTimestamp("ts")); }
|
分析:java.util.Date: 年月日,时分秒
java.sql.Date: 年月日
java.sql.Time: 时分秒
java.sql.Timestamp: 年月日,时分秒 ,毫秒
mysql中的数据类型是datetime,jdbc中使用res.getTimestamp(“列名”)来获取,再转换成java.util.Date(),可以得 到(年月日,时分秒),否则,如果使用res.getDate(“列名”),再转换成java.util.Date则丢失 时分秒(res.getDate()返回java.sql.Date(),只能精确到年月日)
注意:mysql中的timestamp需要3个长度,否则无法保存毫秒值