问题描述
我目前正在构建Spring MVC Web应用程序,数据库是至关重要的后端部分.但是,无论出于何种原因,Spring都拒绝将数据作为UTF-8处理.由于视图,资源和浏览器均设置为Unicode,数据库中的表也设置为Unicode(并且还读取了许多类似的问题),因此我已经确定问题出在数据库连接上.
I'm currently building a Spring MVC webapp and the database is the vital backend part. For whatever reason, however, Spring is refusing to process the data as UTF-8. Since the views, resources and browsers are set to Unicode, and so are the tables in the database (and also reading quite a few similar questions asked), I have established that the problem lies in the database connection.
应该在连接属性中为JDBC驱动程序提供两项:useUnicode(设置为是和characterEncoding(设置为 utf8 ).但是,结果是不可能.
The JDBC Driver should be provided two items in connectionProperties: useUnicode (set to yes and characterEncoding (set to utf8). It turns out, however, it's impossible.
JDBC是bean,因此是通过XML文件配置的,如下所示:
JDBC is a bean, and as such is configured via an XML file, like so:
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/<database>" />
<property name="username" value="<not telling>" />
<property name="password" value="<not telling>" />
此设置会将从数据库中提取的所有非字母数字字符(例如箭头或希腊字母)转换为问号.显然,这是不可接受的.
This setup converts all non-alphanumeric characters pulled from the database (such as arrows or Greek letters) into question marks. Which is, obviously, unacceptable.
我尝试了多种解决方案:将JDBC URL指定为jdbc:mysql://localhost:3306/<database>?useUnicode=yes&characterEncoding=utf8
,与my.ini
文件(和MySQL Workbench)一起播放,以强制将数据库中的所有内容默认设置为utf8
字符集,这引起了最大的麻烦:添加<property name="connectionProperties" value="useUnicode=yes;characterEncoding=utf8" />
.事实证明,在单个bean中设置两个connectionProperty实际上是不可能的,因为...在任何地方都没有提到分隔符(bean将尝试将其读取为试图将yes;characterEncoding=utf8
设置为useUnicode
的值).所以我的问题是:我如何utf8?
I tried multiple solutions: specified the JDBC URL as jdbc:mysql://localhost:3306/<database>?useUnicode=yes&characterEncoding=utf8
, played with my.ini
file (and MySQL Workbench) to force everything in the database to default to utf8
charset, and something that caused the largest headache: adding <property name="connectionProperties" value="useUnicode=yes;characterEncoding=utf8" />
. Turns out, it's literally impossible to set two connectionProperties within a single bean, because... there is no separating character mentioned anywhere (the bean will attempt to read it as trying to set yes;characterEncoding=utf8
as the value of useUnicode
). So my question is: how does I utf8?
推荐答案
该问题可能是由指定 utf8 而不是 UTF-8 引起的.来自使用字符集和Unicode :
The problem may be caused by specifying utf8 and not UTF-8. From Using Character Sets and Unicode:
和 utf8 映射到 UTF-8 .尝试以下JDBC URL:
and utf8 maps to UTF-8. Try the following JDBC URL:
这篇关于如何在Spring管理的MySQL JDBC连接上设置useUnicode = true和characterEncoding = utf8属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!