Gintas_ Gintas_ - 1 year ago 104
SQL Question

Unicode characters saved as � using JDBC, but saved correctly using phpMyAdmin

Here is how I create a connection:

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 = connection.prepareStatement("SET CHARACTER SET utf8");


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ąčęėįšųū");


enter image description here

What is wrong?

If I insert through phpMyAdmin, all good:
enter image description here

Answer Source

In some cases, Java development tools (e.g., Eclipse) use a default character encoding of Cp1252 (a.k.a. windows-1252) for Java source files. That can cause strange encoding issues when working with Unicode characters because the source file encoding affects

  1. how string literals are interpreted, and
  2. the default character set used by the JVM when the project is run from within the IDE.

As in this case, a quick fix is to simply change the source file encoding to UTF-8.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download