Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

problem with utf8 in java

I have the following table:

create table test
(
  fname char(20) character set utf8 collate utf8_turkish_ci,
  id int primary key
);

I am inserting data as follows:

resultSet.executeQuery("set namee utf8");
preparedStatement = connection.prepareStatement("insert into test(fname) values(?)");
preparedStatement.setstring(1,"alis");
preparedStatement.executeUpdate();

But when I retrieve data they are resemble to ?????.

What is problem and how can I solve that?

like image 646
Mahdi_Nine Avatar asked Apr 16 '11 20:04

Mahdi_Nine


People also ask

How do I fix Unmappable character for encoding UTF-8?

Open your file in an editor set to the UTF-8 encoding, fix the quote mark, and save it again. Alternatively, you can find the Unicode point for the character and use a Unicode escape in the source code. For example, the character A can be replaced with the Unicode escape \u0041 .

Why UTF-8 is used in Java?

UTF-8 has the ability to be as condensed as ASCII but can also contain any Unicode characters with some increase in the size of the file. UTF stands for Unicode Transformation Format. The '8' signifies that it allocates 8-bit blocks to denote a character.


1 Answers

As per the MySQL JDBC driver documentation you need to set the character encoding in the JDBC connection URL as well. Here's an example:

jdbc:mysql://localhost:3306/db_name?useUnicode=yes&characterEncoding=UTF-8

Otherwise the MySQL JDBC driver will use the platform default encoding to convert the characters to bytes before sending over network, which is in your case apparently not UTF-8. All uncovered characters will then be replaced by question marks.

Also, when retrieving the data, you need to ensure that the console/file where you're displaying/writing the characters to also supports/uses UTF-8. Otherwise they will become question marks as well. How to fix that depends on how/where you're displaying/writing those characters to.

See also:

  • Unicode - How to get the characters right?

By the way, you don't need the SET NAMES query here.

like image 131
BalusC Avatar answered Sep 27 '22 23:09

BalusC