2016-11-27 85 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

相关问题