Search code examples
sqljdbcunicodeutf-8utf8mb4

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


Here is how I create a connection:

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();

Table:

enter image description here

Inserting:

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();

Result:

enter image description here

What is wrong?

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


Solution

  • 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.