使用JDBC访问mysql数据库进行查询操作,出现中文乱码的结果,然后网上找解决方法,自己捯饬了一下午才解决了,所以想出一个详细的解决方案,可以帮到更多的人少走点弯路http://www/uc/myshow/blog/misc/gif/E___6726EN00SIGG.gif使用JDBC访问mysql数据库进行查询操作,出现中文乱码" TITLE="Eclipse 使用JDBC访问mysql数据库进行查询操作,出现中文乱码" />。
1: 关于connection相关的字符集的官方文档:(先了解才能明白为什么会出现乱码)
-
What character set is the
statement in when it leaves the client?
The server
takes
the character_set_client system
variable to be the character set in which statementsare sent by
the client.
-
What character set should
the server translate a statement to after receiving it?
For this,
the server uses
the character_set_connection and
collation_connection system variables. It converts statements sent
by the client from character_set_client to character_set_connection
(except for string literals that have an introducer such as _latin1
or _utf8). collation_connection is important for comparisons of
literal strings. For comparisons of strings with column values,
collation_connection does not matter because columns have their own
collation, which has a higher collation precedence.
-
What character set should
the server translate to before shipping result sets or error
messages back to the client?
The character_set_results system
variable indicates the character set in
which the server returns query results to the
client. This includes result data such as
column values, and result metadata such as column names and error
messages.
从上文中可以看出character_set_connection、character_set_client、character_set_results三个字符集什么时候用到。从实际上可以看到,当客户端连接服务器的时候,它会将自己想要的字符集名称发给mysql服务器,然后服务器就会使用这个字符集去设置character_set_connection、character_set_client、character_set_results这三个值。
2:为什么会出现乱码?
当你的数据库的字符集和你的Eclipse平台所采用的字符集不同时,从数据库中获得的数据将无法正常的在Eclipse中显示,所以将会出现乱码的情况。(关于字符集的知识详情可以请教度娘查询)
3:如何操作?(仅根据我自身的问题进行阐述)
(1)首先打开mysql的命令行终端查看一下数据库这边字符集的情况:
http://s14/mw690/004aftRczy79FG9sLcV0d&690使用JDBC访问mysql数据库进行查询操作,出现中文乱码" TITLE="Eclipse 使用JDBC访问mysql数据库进行查询操作,出现中文乱码" />
可以看到character_set_connection、character_set_client、character_set_results3个字符集全都是latin1格式。
(2)查看Eclipse这边的字符集情况:
eclipse-->
window-->Preferences-->General-->Workspace-->text
file encoding
这个是选择整体的文件编码方式
可以看到eclipse 这边是默认的GBK格式。
到这里就可以知道问题出在哪里了,是两边的格式不一致,导致了乱码的情况产生!接下来进行修改了。
(3)对数据库这边的格式进行修改
可以直接在命令行进行修改例如下面这样:
但是每次启动数据库服务时都是通过配置文件来进行配置的,有时候这样修改以后但是配置文件并没有修改,所以这次成功了,下一次可能又不成功了,所以最好是通过修改配置文件进行修改。
找到安装mysql的地方找到一个my.ini的配置文件打开,将【mysql】下面的default-character-set=latin1修改为default-character-set=gbk,如下图所示:
保存以后,进行检验一下数据库是否得到了修改(把以前的mysql退出,新打开一个进行检验):
可以发现character_set_connection、character_set_client、character_set_results3个字符集全是GBK格式了。
(4)在更改完格式以后的mysql下面进行重新建表进行实验。这时候就可以进行访问了:
在Eclipse下面进行select * from jdbc_test t where
t.test_id > 3该SQL的查询,结果如下:
加载中,请稍候......