This is how my connection is set:
Connection conn = DriverManager.getConnection(url + dbName + \"?useUnicode=true&characterEncoding=utf-8\", userName, password
Got the same problem, to save the data with utf8mb4
needs to make sure:
character_set_client, character_set_connection, character_set_results
are utf8mb4
: character_set_client
and character_set_connection
indicate the character set in which statements are sent by the client, character_set_results
indicates the character set in which the server returns query results to the client.
See charset-connection.
the table and column encoding is utf8mb4
For JDBC, there are two solutions:
modify my.cnf
like the following and restart MySQL:
[mysql]
default-character-set=utf8mb4
[mysqld]
character-set-server=utf8mb4
collation-server=utf8mb4_unicode_ci
this can make sure the database and character_set_client, character_set_connection, character_set_results
are utf8mb4
by default.
restart MySQL
change the table and column encoding to utf8mb4
STOP specifying characterEncoding=UTF-8
and characterSetResults=UTF-8
in the jdbc connector,cause this will override character_set_client
, character_set_connection
, character_set_results
to utf8
change the table and column encoding to utf8mb4
specifying characterEncoding=UTF-8
in the jdbc connector,cause the jdbc connector doesn't suport utf8mb4
.
write your sql statment like this (need to add allowMultiQueries=true
to jdbc connector):
'SET NAMES utf8mb4;INSERT INTO Mytable ...';
this will make sure each connection to the server, character_set_client,character_set_connection,character_set_results
are utf8mb4
.
Also see charset-connection.