Can't store UTF-8 Content in MySQL Using Java PreparedStatement

后端 未结 6 1935
逝去的感伤
逝去的感伤 2020-12-18 07:29

For some strange reason I can\'t seem to add UTF-8 data to my MySQL database. When I enter a non-latin character, it\'s stored as ?????. Everything else is stored fine. S

6条回答
  •  醉酒成梦
    2020-12-18 07:44

    There is 2 points in the mysql server to check in order to correctly set the UTF-8 charset.

    Database Level

    This is obtained by creating it :

    CREATE DATABASE 'db' CHARACTER SET 'utf8';
    

    Table Level

    All of the tables need to be in UTF-8 also (which seems to be the case for you)

    CREATE TABLE  `Table1` (
        [...]
    ) DEFAULT CHARSET=utf8 COLLATE=utf8_general_ci;
    

    The important part being DEFAULT CHARSET=utf8 COLLATE=utf8_general_ci

    Finally, if your code weren't handling utf8 correctly, you could have forced your JVM to use utf8 encoding by changing the settings by on startup :

    java -Dfile.encoding=UTF-8 [...]
    

    or changing the environment variable

    "**JAVA_TOOLS_OPTIONS**" to -Dfile.encoding="UTF-8"
    

    or programmatically by using :

    System.setProperty("file.encoding" , "UTF-8");
    

    (this last one may not have the desire effect since the JVM caches value of default character encoding on startup)

    Hope that helped.

提交回复
热议问题