AdSense

網頁

2017/8/15

MySQL Exception錯誤訊息參數中文亂碼

在Java JDBC連線MySQL資料庫時,若執行錯誤會丟出Exception錯誤訊息,但錯誤訊息中的中文參數在Eclipse的console出現亂碼如下

嚴重: Servlet.service() for servlet [dispatcher] in context with path [/moneynote] threw exception [Request processing failed; nested exception is org.springframework.dao.DuplicateKeyException: StatementCallback; SQL [INSERT INTO tb_catg VALUES('測試類別001' ,NOW(),NOW())]; Duplicate entry '測試類別001' for key 'PRIMARY'; nested exception is com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Duplicate entry '測試類別001' for key 'PRIMARY'] with root cause 
com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Duplicate entry '測試類別001' for key 'PRIMARY'
 at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
 at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)

這問題困擾了我有半天之久,原本一直以為是MySQL的character set設定有問題,但都設成utf-8也是無解,最後懷疑Exception是從jdbc丟出噴出才google到解答

解決方式很簡單,就是將MySQL的jdbc driver更新到較新的版本,例如上面出現問題的jdbc版本為5.1.8,更新到5.1.40後就解決了,更新後正常顯示如下。

嚴重: Servlet.service() for servlet [dispatcher] in context with path [/moneynote] threw exception [Request processing failed; nested exception is org.springframework.dao.DuplicateKeyException: StatementCallback; SQL [INSERT INTO tb_catg VALUES('測試類別001',NOW(),NOW())]; Duplicate entry '測試類別001' for key 'PRIMARY'; nested exception is com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Duplicate entry '測試類別001' for key 'PRIMARY'] with root cause
com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: 
Duplicate entry '測試類別001' for key 'PRIMARY'
 at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
 at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)

沒有留言:

AdSense