MySQL查詢預設時間拋出異常

來源:互聯網
上載者:User

MySQL查詢預設時間拋出異常

問題現象

建立了一個MySQL表,表中有一個欄位是Date類型的,預設值時0000-00-00 00:00:00,查詢的時候使用的是PrepareStatement,查詢結果為ResultSet,從結果中取出Date欄位使用的是ResultSet.getDate("XXXX"), 結果會拋出異常:java.sql.SQLException:Value '0000-00-00' can not be represented as java.sql.Date.

問題原因

MySQL中Date的預設值是"0000-00-00 00:00:00",但是java.sql.Date卻認為這是一個不合法的值,所以會拋出上述異常。

解決方案

在MySQL的串連的URL中增加一個參數zeroDateTimeBehavior,這個參數可以指定遇到這樣的預設值時將這個值轉換為什麼值。 有兩種方案,一種是轉換為"0001-01-01 00:00:00", 另一種方案則直接轉換為Null. 依次對應的具體配置如下:

String url = "jdbc:mysql://localhost:3306/test?zeroDateTimeBehavior=round";  // 轉換為 "0001-01-01 00:00:00"

String url = "jdbc:mysql://localhost:3306/test?zeroDateTimeBehavior=convertToNull";  // 轉換為Null

本文永久更新連結地址:

相關文章

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.