mysql连接异常java.sql.SQLException: Value '0000-00-00' can not be represented as java.sql.Date

JAVA连接MySQL数据库,在操作值为0的timestamp类型时不能正确的处理,而是默认抛出一个异常,就是所见的:java.sql.SQLException: Cannot convert value '0000-00-00 00:00:00' from column 7 to TIMESTAMP。

这一问题在官方文档中有详细说明,详见如下链接: http://bugs.mysql.com/bug.php?id=19274 http://dev.mysql.com/doc/refman/5.5/en/connector-j-installing-upgrading.html 

在JDBC连接串中有一项属性:zeroDateTimeBehavior,可以用来配置出现这种情况时的处理策略,该属性有下列三个属性值:

  1. l exception:默认值,即抛出SQL state [S1009]. Cannot convert value....的异常;

  2. l convertToNull:将日期转换成NULL值;

  3. l round:替换成最近的日期即0001-01-01;

因此对于这类异常,可以考虑通过修改连接串,附加zeroDateTimeBehavior=convertToNull属性的方式予以规避,

例如: jdbc:mysql://localhost:3306/mydbname?zeroDateTimeBehavior=convertToNull 从另一个层面讲,这类异常的触发也与timestamp赋值的操作有关,如果能够在设计阶段和记录写入阶段做好逻辑判断,避免写入 '0000-00-00 00:00:00'这类值,那么也可以避免出现Cannot convert value '0000-00-00 00:00:00' from column N to TIMESTAMP的错误。

java.sql.SQLException: Value '0000-00-00 00:00:00' can not be represented as java.sql.Timest 错误问题是时间类型存储错误,解决方案:    jdbc.url=jdbc:mysql:ip地址:端口号数据库名称?characterEncoding=utf8&zeroDateTimeBehavior=convertToNull解决方案即是url后面添加加参数:zeroDateTimeBehavior=convertToNull此参数是指定时间类型错误处理策略为:错误则指定为null策略:    1.exception(不指定,则默认)---->默认抛出异常,    2.convertToNull------->转化为null    3.round------->替换成最近的日期即XXXX-01-01
 

解决办法:


在jdbc的url加上   zeroDateTimeBehavior参数:


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


对于值为0000-00-00   00:00:00(默认值)的纪录,根据不同的配置,会返回不同的结果:


不配置:默认返回异常


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


zeroDateTimeBehavior=convertToNull   null


但 这样有可能会报新的Exception:


The reference to entity "characterEncoding" must end with the ';' delimiter   


其原因可能是在Properties文件或者xml文件中忘记进行特殊符号的转译了,


jdbc:mysql://192.168.1.155:3306/diandi?useUnicode=true&characterEncoding=UTF-8 & zeroDateTimeBehavior=convertToNull


需要改为:


jdbc:mysql://192.168.1.155:3306/diandi?useUnicode=true&characterEncoding=UTF-8 & zeroDateTimeBehavior=convertToNull 


有以下几类字符要进行转义替换:


&lt;  <  小于号


&gt; >  大于号


&amp; &  和


&apos; '  单引号


&quot;  "  双引号

 

猜你喜欢

转载自blog.csdn.net/weixin_41577923/article/details/83014416
今日推荐