2016-11-27 90 views
1

這裏是如何創建一個連接:Unicode字符保存爲使用JDBC,但可以正確保存使用phpMyAdmin

Class.forName("com.mysql.jdbc.Driver"); 
Properties properties = new Properties(); 
properties.setProperty("user", "root"); 
properties.setProperty("password", "PASSWORD"); 
properties.setProperty("useSSL", "false"); 
properties.setProperty("autoReconnect", "true"); 
properties.setProperty("useUnicode", "true"); 
properties.setProperty("characterEncoding", "UTF-8"); 
Connection connection = DriverManager.getConnection("jdbc:mysql://localhost/coolpoop", properties); 

PreparedStatement statement = connection.prepareStatement("SET NAMES 'utf8'"); 
statement.execute(); 
statement = connection.prepareStatement("SET CHARACTER SET utf8"); 
statement.execute(); 

表:

enter image description here

插入:

PreparedStatement state = Mysql.conn().prepareStatement("insert into contents(campaignId, site_id, original_article_id, title, content) values(-1, -1, -1, ?, ?)"); 
state.setString(1, "acbdąčęėįšųū"); 
state.setString(2, "acbdąčęėįšųū"); 
state.execute(); 

結果:

enter image description here

出了什麼問題?

EDIT1: 如果我通過phpMyAdmin的,都好插入: enter image description here

+0

什麼是您的數據庫編碼?你可以通過db客戶端插入UTF-8符號嗎? – borowis

+1

@BorysZibrov查看EDIT1。沒有檢查數據庫編碼,但我懷疑它應該沒問題,如果我可以插入通過phpMyAdmin –

+0

是的,那麼數據庫是好的,謝謝 – borowis

回答

1

在某些情況下,Java開發工具(例如Eclipse的)使用的Cp1252 Java源文件默認字符編碼(又名windows-1252)。 Unicode字符工作時可能會導致奇怪的編碼問題,因爲源文件編碼影響

  1. 如何字符串字面解釋,並
  2. 默認字符集由JVM使用時,該項目從IDE中運行。

正如在這種情況下,一個快速解決方法是簡單地將源文件編碼更改爲UTF-8

相關問題