Cannot convert value '0000-00-00 00:00:00' from column XX to TIMESTAMP

1.问题

程序使用select 语句从中取数据时出现以下异常:

java.sql.SQLException: Cannot convert value '0000-00-00 00:00:00' from column 9 to TIMESTAMP.
 at com.mysql.jdbc.ResultSet.getTimestampFromBytes(ResultSet.java:6864)
 at com.mysql.jdbc.ResultSet.getTimestampInternal(ResultSet.java:6899)
 at com.mysql.jdbc.ResultSet.getTimestamp(ResultSet.java:6218)
 at com.mysql.jdbc.ResultSet.getTimestamp(ResultSet.java:6256)
 at org.hibernate.type.TimestampType.get(TimestampType.java:30)
 at org.hibernate.type.NullableType.nullSafeGet(NullableType.java:113)
 at org.hibernate.type.NullableType.nullSafeGet(NullableType.java:102)

猜想数据库表中有的记录  time字段   其值为:“0000-00-00 00:00:00”

2.合理解释

在Mysql数据库中使用DATETIME类型来存储时间,使用JDBC中读取这个字段的时候,应该使用 ResultSet.getTimestamp(),这样会得到一个java.sql.Timestamp类型的数据。在这里既不能使用 ResultSet.getDate(),也不能使用ResultSet.getTime(),因为前者不包括time数据,后者不包括date数据。

但是在使用ResultSet.getTimestamp()时也不是完全安全的,例如,当数据库中的  TIMESTAMP   /  DATETIME  类型的字段值为 '0000-00-00 00:00:00'时,使用此方法进行读取,会抛出异常:Cannot convert value '0000-00-00 00:00:00' from column 1 to TIMESTAMP,这是因为JDBC不能将'0000-00-00 00:00:00'转化为一个为一个java.sql.Timestamp,在Java中,想创建一个java.util.Date,使其值为 '0000-00-00'也是不可能的,最古老的日期应该是'0001-01-01 00:00:00'。
 

查看了mysql5的帮助文档对于datetime的解释如下

Datetimes with all-zero components (0000-00-00 ...) — These values can not be represented 关于所有Datetime类型由0组成的数据,这些值不能在java中被可靠的表示
reliably in Java. 
Connector/J 3.0.x always converted them to NULL when being read from a ResultSet. 
当这些值正在从ResultSet容器中读取时候,Connector/J 3.0.x 一直把他们转换为NULL值。

Connector/J 3.1 throws an exception by default when these values are encountered as this is the most correct behavior according to the JDBC and SQL standards.
依照JDBC和SQL的标准这些值碰到的最正确的处理方式就是在缺省情况下产生异常
This behavior can be modified using the zeroDateTimeBehavior configuration property. The allowable values are: 
JDBC允许用下列的值对zeroDateTimeBehavior 属性来设置这些处理方式,

exception (the default), which throws an SQLException with an SQLState of S1009. 
设置为exception 异常(缺省)用一个SQLState的s1009错误号来抛出一个异常
convertToNull, which returns NULL instead of the date. 
设置为convertToNull,用NULL值来代替这个日期类型
round, which rounds the date to the nearest closest value which is 0001-01-01. 
设置为round,则围绕这个日期最接近的值(0001-01-01)来代替

3.解决方案

给jdbc   url加上   zeroDateTimeBehavior参数: 

datasource.url=jdbc:mysql://localhost:3306/pe?
useUnicode=true&characterEncoding=gbk&zeroDateTimeBehavior=convertToNull 


zeroDateTimeBehavior=round

是MySql中的DateTime字段默认值查询时的处理方式;默认是抛出异常, 

对于值为0000-00-00   00:00:00(默认值)的纪录,

如下两种配置,会返回不同的结果: 

zeroDateTimeBehavior=round   0001-01-01   00:00:00.0 

zeroDateTimeBehavior=convertToNull    null


 

猜你喜欢

转载自blog.csdn.net/Architect_CSDN/article/details/93307040
今日推荐