Home > Database > Mysql Tutorial > 解决Java程序使用MySQL时返回参数为乱码的示例教程_MySQL

解决Java程序使用MySQL时返回参数为乱码的示例教程_MySQL

WBOY
Release: 2016-05-27 13:46:04
Original
1012 people have browsed it

先说MySQL的字符集问题。Windows下可通过修改my.ini内的 

default-character-set=utf8  //客户端的默认字符集

Copy after login

在MySQL客户端工具中输入

SHOW VARIABLES LIKE 'character%'; 
Copy after login

显示如下

2015129110019784.png (318×140)

这样执行读取信息返回中文为乱码,解决办法是,在连接数据库之后,读取数据之前,先执行一项查询 SET NAMES 'utf8'; 即可显示正常。

最简单的完美修改方法,修改mysql的my.cnf文件中的字符集键值(注意配置的字段细节):

1、在[client]字段里加入default-character-set=utf8,如下:

port = 3306 
socket = /var/lib/mysql/mysql.sock 
default-character-set=utf8 

Copy after login

2、在[mysqld]字段里加入character-set-server=utf8,如下:

port = 3306 
socket = /var/lib/mysql/mysql.sock 
character-set-server=utf8 

Copy after login

3、在[mysql]字段里加入default-character-set=utf8,如下:

no-auto-rehash 
default-character-set=utf8 

Copy after login

修改完成后,service mysql restart重启mysql服务就生效。注意:[mysqld]字段与[mysql]字段是有区别的。这点在网上没人反馈过。

使用SHOW VARIABLES LIKE ‘character%';查看,发现数据库编码全已改成utf8。

+--------------------------+----------------------------+ 
| Variable_name | Value | 
+--------------------------+----------------------------+ 
| character_set_client | utf8 | 
| character_set_connection | utf8 | 
| character_set_database | utf8 | 
| character_set_filesystem | binary | 
| character_set_results | utf8 | 
| character_set_server | utf8 | 
| character_set_system | utf8 | 
| character_sets_dir | /usr/share/mysql/charsets/ | 
+--------------------------+----------------------------+ 

Copy after login


4、如果上面的都修改了还乱码,那剩下问题就一定在connection连接层上。解决方法是在发送查询前执行一下下面这句(直接写在SQL文件的最前面):

SET NAMES ‘utf8′; 
Copy after login

它相当于下面的三句指令:

SET character_set_client = utf8; 
SET character_set_results = utf8; 
SET character_set_connection = utf8; 

Copy after login


网上很多其他方法不能彻底解决这个问题,这个可以完美解决!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template