JDBC: Insert Unicode UTF-8 Characters into MySQL

Just a quick heads up if you're looking to insert for example Japanese characters into a MySQL database.

You're using JDBC to insert strings with unicode characters from your Java application and are seeing ??? or empty strings instead of ゼロ in your database.

How to fix it:

  1. First:

    If your Java application is reading the data from for example a text file. Make sure you have specified the right characters encoding in your call to the input stream. It should look something like this:

    BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(filePath), StandardCharsets.UTF_8));
    
  2. Second:

    Make sure you tell JDBC which encoiding to use. This is done as part of the query string when connecting to the DB.

    Notice this part: ?useUnicode=yes&characterEncoding=UTF-8. This is where the magic happens.

    Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/sample?useUnicode=yes&characterEncoding=UTF-8", "username", "password");
    
  3. Third:

    Ensure your table uses UTF-8. I usually go with "Encoding: UTF-8 Unicode(utf8)" and "Collation: utf8_bin"

Comments

Popular posts from this blog

Reduce TIME_WAIT Socket Connections