“Incorrect string value” when trying to insert UTF-8 into MySQL via JDBC?

前端 未结 18 942
无人及你
无人及你 2020-11-22 07:51

This is how my connection is set:
Connection conn = DriverManager.getConnection(url + dbName + \"?useUnicode=true&characterEncoding=utf-8\", userName, password

18条回答
  •  难免孤独
    2020-11-22 08:09

    Got the same problem, to save the data with utf8mb4 needs to make sure:

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

    2. the table and column encoding is utf8mb4

    For JDBC, there are two solutions:

    Solution 1 (need to restart MySQL):

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

    1. restart MySQL

    2. change the table and column encoding to utf8mb4

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

    Solution two (don't need to restart MySQL):

    1. change the table and column encoding to utf8mb4

    2. specifying characterEncoding=UTF-8 in the jdbc connector,cause the jdbc connector doesn't suport utf8mb4.

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

提交回复
热议问题