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:
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:
What is wrong?
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
As in this case, a quick fix is to simply change the source file encoding to UTF-8
.