rvduyw
Last Updated: February 25, 2016
·
24.12K
· moezzie
43d2fb9cdafaaaaa0848cb637bc6aabc

JDBC: Inserting unicode UTF-8 characters into MySQL

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

Case:

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

How to fix it:

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), "UTF-8" )  );

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/dbname?useUnicode=yes&characterEncoding=UTF-8","username", "password");

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

Cheers,

May the code be with you!

Say Thanks
Respond

2 Responses
Add your response

21284
0 1p n0pv5x8txuj0jxszntr85kkfieyxy14z4v69kqqjcfu2lnounc9zkga ouujdyscztxbxhfdgd4hls7qecbvhsfd dzegs7qvpqflq64fimp39orry 3qdtcp8z0u12gsunzwiuv

try {
Statement stmt;
ResultSet rs;
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/arabic?useUnicode=yes&characterEncoding=UTF-8";
Connection con = (Connection) DriverManager.getConnection(url, "root", "root");

   // con.setCharacterEncoding("utf-8");
    stmt = (Statement) con.createStatement();
    stmt.executeQuery("SET NAMES 'UTF8'");
    stmt.executeQuery("SET CHARACTER SET 'UTF8'");
    String greekname = "κωνσταντίνα";
    stmt.executeUpdate("INSERT INTO categories(category_id,category_name) VALUES ('" + 17 + "','" + greekname + "')");
    con.close();
} catch (Exception e) {
    System.out.println("problem during the connection with the database!"+e);
}
over 1 year ago ·
22491
None

Awesome it works for me & solve my proublem.

Thanks
Sachin

over 1 year ago ·