使用 JDBC 连接器 5.1 从 Java 读取/写入 MySQL 中的 UTF-8 数据时出现问题

问题描述:

我有一个包含两个 MySQL 数据库(UTF-8)的场景,一个同步两个数据库的 Java 代码(一个定时器服务)(首先读取它们的表单,然后写入/更新到第二个)和一个允许修改的 Web 应用程序数据加载到第二个数据库中.

I have a scenario with two MySQL databases (in UTF-8), a Java code (a Timer Service) that synchronize both databases (reading form first of them and writing/updating to second) and a Web application that lets modify data loaded in the second database.

所有数据库访问都是使用 IBATIS 进行的(但我发现我在使用 JDBC、PreparedStatements 和 ResultSets 时遇到了同样的问题)

All database access is made using IBATIS (but I detect that I have the same problem using JDBC, PreparedStatements and ResultSets)

当我的 java 代码从第一个数据库读取数据时,我获得了像 'ó' 这样的字符,而实际上它必须是 'ó'.该数据是在不修改第二个数据库的情况下写入的.

When my java code reads data from first database, I obtain characters like 'ó' when really it must be 'ó'. This data is wroten without modifications to the second database.

后来,当我在 Web 应用程序中看到加载的数据时,尽管 <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>.

Later, when I see the loaded data in my web application, I see the extrange character despite the <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />.

如果我使用...解码数据

If I decode the data using ...

new String(data.getBytes("UTF-8"));

... 我正确地形象化了字符 (ó).但是我不能将此解决方案用作一般规则,因为当我使用 Web 应用程序表单修改数据时,数据不会在我的第二个数据库中以 UTF-8 更新(尽管数据库是 UTF-8 并且我的连接字符串使用的是字符编码,characterSetResults 和 useUnicode 参数).

... I visualize correctly the character (ó). But I can not use this solution as a general rule because when I modify data using web application form, the data is not updated in UTF-8 in my second database (despite the database is UTF-8 and my connection string is using characterEncoding, characterSetResults and useUnicode parameters).

从我的 Java 代码中,我获得了以下数据库设置:

From my Java code I obtain the following Database settings:

character_set_client-->utf8 
character_set_connection-->utf8 
character_set_database-->utf8 
character_set_filesystem-->binary 
character_set_results-->utf8 
character_set_server-->latin1 
character_set_system-->utf8 
character_sets_dir-->/usr/local/mysql51/share/mysql/charsets/ 

character_set_server 设置无法更改,我不知道我做错了什么!!

the character_set_server setting can't be changed and I don't know what I am doing wrong!!

如何使用 JDBC 连接器 (mysql-connector-java-5.1.5-bin.jar) 从 MySQL 读取 UTF-8 数据?

How can I read UTF-8 data from MySQL using JDBC connector (mysql-connector-java-5.1.5-bin.jar)?

是从第一个数据库读取数据还是写入第二个数据库有问题?

Is the problem with reading data from the first database or writing to the second database?

有点晚了,但这对你有帮助:

A little late but this will help you:

DriverManager.getConnection(
           "jdbc:mysql://" + host + "/" + dbName 
           + "?useUnicode=true&characterEncoding=UTF-8", user, pass);