How to correctly write UTF-8 strings into MySQL through JDBC interface

Solution 1:

Ensure that your MySQL configuration encoding is defined correctly. Check your settings and the correctness of the modifications with these commands:

show variables like 'character%';

and show variables like 'collation%';

Add these lines to either my.cnf or my.ini:

For MySQL 5.1.nn, and later versions 5.5.29 you just need these two lines:

[mysqld]
character-set-server = utf8
character-set-filesystem = utf8

For MySQL 5.0.nn and older use these settings:

[client]
default-character-set=utf8


[mysql]
default-character-set=utf8


[mysqld]
default-character-set=utf8
character-set-server=utf8

It is probably more convenient to use MySQL-Workbench for your settings. Versions 5+ are excellent.

enter image description here

In your Java program connect like this:

con = DriverManager.getConnection("jdbc:mysql://localhost:3306/myDatabase?useUnicode=true&characterEncoding=UTF-8","user","passwd");

Solution 2:

If you get ????????? add the parameter characterEncoding=utf-8 instead of useUnicode=true. See the following examples.

For english text:

String url =  "jdbc:mysql://localhost:" + port + "/DBName?useUnicode=true&...";

For text in russian laguage:

String url = "jdbc:mysql://localhost:" + port + "/DBName&characterEncoding=utf-8&...";