1、知識掃盲java
JDBC:全稱是java DataBase Connectivity
中文意思是java數據庫鏈接
解釋就是用於java編程語言和數據庫之間的數據庫無關的標準java APImysql
2、錯誤展現sql
錯誤很差描述,直接看圖:
數據庫
3、分析緣由編程
在服務器上執行「date」,看到時間,看到有CST字樣
[root@dabiaoge ~]# date
Wed Jan 9 21:54:23 CST 2019
繼續知識點掃盲:
CST時區
名爲CST的時區是一個很混亂的時區,有四種含義:服務器美國中部時區Central Standard Time(USA)UTC-06:00
澳大利亞中部時區中央標準時間(澳大利亞)UTC + 09:30
中國標準時中國標準時區UTC + 08:00
古巴標準時古巴標準時區UTC-04:00session緣由:CST的時區是一個很混亂的時區,在與MySQL協商會話時區時,Java會誤覺得是CST -0500或者CST -0600,而非CST +0800app
解釋緣由是什麼意思:
先來了解下美國的時區變化歷史,美國規定每一年從「3月11日」至「11月7日」實行夏令時,美國中部時區改成UTC-05:00;而「11月7日」至「3月11日」實行冬令時,美國中部時區改成UTC-06:00,博主的線上問題發現的時間是2019年1月9日,而此時美國中部的時區是UTC0600,而咱們的時區是UTC0800,因此6+8=14個小時,所以線上的錯誤時間相隔14個小時。編程語言
4、排錯過程ide
在項目中,偶然發現數據庫中存儲的 Timestamp 字段的 unix_timestamp() 值比真實值少了 14 個小時。經過調試追蹤,發現了 com.mysql.cj.jdbc 裏的時區協商有問題。
當 JDBC 與 MySQL 開始創建鏈接時,會調用 com.mysql.cj.jdbc.ConnectionImpl.initializePropsFromServer() 獲取服務器參數,其中咱們看到調用 this.session.configureTimezone() 函數,它負責配置時區。
public void configureTimezone() { String configuredTimeZoneOnServer = getServerVariable("time_zone"); if ("SYSTEM".equalsIgnoreCase(configuredTimeZoneOnServer)) { configuredTimeZoneOnServer = getServerVariable("system_time_zone"); } String canonicalTimezone = getPropertySet().getStringReadableProperty(PropertyDefinitions.PNAME_serverTimezone).getValue(); if (configuredTimeZoneOnServer != null) { // user can override this with driver properties, so don't detect if that's the case if (canonicalTimezone == null || StringUtils.isEmptyOrWhitespaceOnly(canonicalTimezone)) { try { canonicalTimezone = TimeUtil.getCanonicalTimezone(configuredTimeZoneOnServer, getExceptionInterceptor()); } catch (IllegalArgumentException iae) { throw ExceptionFactory.createException(WrongArgumentException.class, iae.getMessage(), getExceptionInterceptor()); } } } if (canonicalTimezone != null && canonicalTimezone.length() > 0) { this.serverTimezoneTZ = TimeZone.getTimeZone(canonicalTimezone); // The Calendar class has the behavior of mapping unknown timezones to 'GMT' instead of throwing an exception, so we must check for this... if (!canonicalTimezone.equalsIgnoreCase("GMT") && this.serverTimezoneTZ.getID().equals("GMT")) { throw ... } } this.defaultTimeZone = this.serverTimezoneTZ; }
追蹤代碼可知,當 MySQL 的 time_zone 值爲 SYSTEM 時,會取 system_time_zone 值做爲協調時區。
讓咱們登陸到 MySQL 服務器驗證這兩個值:
mysql> show variables like '%time_zone%'; +------------------+--------+ | Variable_name | Value | +------------------+--------+ | system_time_zone | CST | | time_zone | SYSTEM | +------------------+--------+ 2 rows in set (0.00 sec)
重點在這裏!若 String configuredTimeZoneOnServer 獲得的是 CST 那麼 Java 會誤覺得這是 CST -0600 ,所以 TimeZone.getTimeZone(canonicalTimezone) 會給出錯誤的時區信息。debug variables
本機默認時區是 Asia/Shanghai +0800 ,誤認爲服務器時區爲 CST -0600 ,實際上服務器是 CST +0800 。咱們會想到,即使時區有誤解,若是 Timestamp 是以 long 表示的時間戳傳輸,也不會出現問題,下面讓咱們追蹤到 com.mysql.cj.jdbc.PreparedStatement.setTimestamp()
public void setTimestamp(int parameterIndex, Timestamp x) throws java.sql.SQLException { synchronized (checkClosed().getConnectionMutex()) { setTimestampInternal(parameterIndex, x, this.session.getDefaultTimeZone()); } }
注意到這裏 this.session.getDefaultTimeZone() 獲得的是剛纔那個 CST -0600
private void setTimestampInternal(int parameterIndex, Timestamp x, TimeZone tz) throws SQLException { if (x == null) { setNull(parameterIndex, MysqlType.TIMESTAMP); } else { if (!this.sendFractionalSeconds.getValue()) { x = TimeUtil.truncateFractionalSeconds(x); } this.parameterTypes[parameterIndex - 1 + getParameterIndexOffset()] = MysqlType.TIMESTAMP; if (this.tsdf == null) { this.tsdf = new SimpleDateFormat("''yyyy-MM-dd HH:mm:ss", Locale.US); } this.tsdf.setTimeZone(tz); StringBuffer buf = new StringBuffer(); buf.append(this.tsdf.format(x)); if (this.session.serverSupportsFracSecs()) { buf.append('.'); buf.append(TimeUtil.formatNanos(x.getNanos(), true)); } buf.append('\''); setInternal(parameterIndex, buf.toString()); } }
原來 Timestamp 被轉換爲會話時區的時間字符串了。問題到此已然明晰:
JDBC 誤認爲會話時區在 CST-6
JBDC 把 Timestamp+0 轉爲 CST-6 的 String-6
MySQL 認爲會話時區在 CST+8,將 String-6 轉爲 Timestamp-14最終結果相差 14個小時!若是處在夏令時還會相差 13個小時
5、解決方法
解決辦法很是的簡單,手動明確指定 MySQL 數據庫的時區,不使用引起誤解的 CST:
臨時生效:
mysql> set global time_zone = '+08:00';
Query OK, 0 rows affected (0.00 sec)mysql> set time_zone = '+08:00';
Query OK, 0 rows affected (0.00 sec)永久生效(修改後須要重啓mysql):
修改 my.cnf 文件,在 [mysqld] 節下增長 default-time-zone = '+08:00'