MySQL解决中文乱码问题的通用方法的详细总结

[size=large]一MySQL解决乱码问题步骤概括[/size]
1、所有请求都编码都统一用utf-8,
2、使用Filter过滤所有request和response都设成utf-8,
3、数据库character_set_database设置utf-8,
4、假如character_set_client还是默认的latin1,要在连接数据库时url后面加上转码:
jdbc:mysql://localhost:3306/databasename?useUnicode=true&characterEncoding=utf-8
或者
jdbc:mysql://localhost:3306/databasename?useUnicode=true&characterEncoding=utf-8
如果用的是hibernate
在<session-factory>和</ session-factory>之间加入这么一段:
代码:
<property name="connection.useUnicode">true</property>
<property name="connection.characterEncoding">utf-8</property>
5、对于用javascript传递中文参数,要对中文参数字段进行编码,解码
在发送页面要指定编码
例如: str = encodeURI(str); (encodeURI转码后为utf-8)
在接收页面要进行转码
例如: str = new String(str.getBytes("iso-8859-1"),"utf-8");


[size=large]二MySQL解决乱码问题具体操作[/size]
1、修改数据库方法如下:
ALTER DATABASE sample ####这里修改整个数据库的编码
CHARACTER SET utf8
DEFAULT CHARACTER SET utf8
COLLATE utf8_general_ci
DEFAULT COLLATE utf8_general_ci;
当然了,你也可在在建数据库的时候指定编码,比如:
CREATE DATABASE sample
CHARACTER SET utf8
DEFAULT CHARACTER SET utf8
COLLATE utf8_general_ci
DEFAULT COLLATE utf8_general_ci ;

2、建表的语句
CREATE TABLE `mysqlcode` (
`id` TINYINT( 255 ) UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY ,
`content` VARCHAR( 255 ) NOT NULL
) TYPE = MYISAM CHARACTER SET gbk COLLATE gbk_chinese_ci;

其中后面的TYPE = MYISAM CHARACTER SET gbk COLLATE gbk_chinese_ci;就是指定数据库的字符集,COLLATE (校勘),让mysql同时支持多种编码的数据库。

当然我们也可以通过如下指令修改数据库的字符集
alter database da_name default character set 'charset'.

3、接下来要做的是打开mysql所在的目录下的my.nin
[client]
port=3306
[mysql]
default-character-set=gbk
[mysqld]
default-character-set=utf8
#重要:这个设置决定MySQL的工作环境的字符集!数据库继承MySQL设置的字符集,而表则继承数据库的字符集,字段则继承表的字符集!所以这里设置很重要!

启动mysql,输入:
执行下列语句,可以查看结果:
mysql> SHOW VARIABLES LIKE '%character%' ;
mysql> SHOW VARIABLES LIKE '%collation%' ;

修改mysql 字符设置,可以采用下述配置(客户端以utf8格式发送 ):
SET character_set_client='utf8' 客户端字符
SET character_set_connection='utf8'
SET character_set_results='utf8'

上面的三行配置就等价于 SET NAMES 'utf8'。
现在用DOS命令 对刚才创建的数据库操作
mysql> use test;
Database changed
mysql> insert into mysqlcode values(null,'php爱好者');
ERROR 1406 (22001): Data too long for column 'content' at row 1
没有指定字符集为gbk,插入时出错
前面插入下面一条语句就可以啦
mysql> set names 'gbk';
Query OK, 0 rows affected (0.02 sec)
mysql> insert into mysqlcode values(null,'php爱好者');
Query OK, 1 row affected (0.00 sec)
制定字符集为gbk,插入成功

4、用到过滤器
有关filter设定的具体代码在文章末尾
然后在web.xml中配置filter(一定要配置在struts filter 之前)
<!-- 解决中文乱码问题 -->
<filter>
<filter-name>encodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>GBK</param-value>
</init-param>
</filter>

<filter-mapping>
<filter-name>encodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>

5.js 编码
js中escape,encodeURI,encodeURIComponent三个函数的区别
js对文字进行编码涉及3个函数:escape,encodeURI,encodeURIComponent,相应3个解码函数:unescape,decodeURI,decodeURIComponent
a、传递参数时需要使用encodeURIComponent,这样组合的url才不会被#等特殊字符截断。
例如:<script language="javascript">document.write('<a href="http://passport.baidu.com/?logout&aid=7&u='+encodeURIComponent("http://cang.baidu.com/bruce42")+'">退出</a>');</script>
b、进行url跳转时可以整体使用encodeURI
例如:Location.href=encodeURI("http://cang.baidu.com/do/s?word=百度&ct=21");
c、js使用数据时可以使用escape
[Huoho.Com编辑]
例如:搜藏中history纪录。
d、escape对0-255以外的unicode值进行编码时输出%u****格式,其它情况下escape,encodeURI,encodeURIComponent编码结果相同。
最多使用的应为encodeURIComponent,它是将中文、韩文等特殊字符转换成utf-8格式的url编码,所以如果给后台传递参数需要使用encodeURIComponent时需要后台解码对utf-8支持(form中的编码方式和当前页面编码方式相同)
escape不编码字符有69个:*,+,-,.,/,@,_,0-9,a-z,A-Z
encodeURI不编码字符有82个:!,#,$,&,',(,),*,+,,,-,.,/,:,;,=,?,@,_,~,0-9,a-z,A-Z
encodeURIComponent不编码字符有71个:!, ',(,),*,-,.,_,~,0-9,a-z,A-Z

[size=large]三 MySQL中文乱码解决方案集锦[/size]
1.建立数据库是一般的语句: create database dbname;
2.在库中建表时语句为:
create table tbname(..........)engine=MyISAM character set gbk collate gbk_chinese_ci;
3.程序中连接数据库的Connection对象需要写成Connection con = DriverManaager.getConnection("jdbc:mysql://...user=..&password=...&useUnicode=true&characterEncoding=gbk");
4.若在终端下用mysql命令向数据库插入数据,则在进入mysql时的命令写成:#mysql --default-character-set=gbk -u ... –p
5.常用的修改语句:
alter database 'test' default character set utf8 collate utf8_bin
alter table 'category' default character set utf8 collate utf8_bin
alter table 'test' change 'dd' 'dd' varchar(45) character set utf8 collate utf8_bin
mysql_connect('localhost','user','password');
mysql_select_db('my_db');
mysql_query("set names utf8;");
mysql_query("set character set utf8");
6.在jsp页面的编码设置为utf-8.


[size=large]四 关于MySQL(4.1以后版本) 服务器中的六个关键位置字符集的概念[/size]
client 、connection、database、results、server 、system。
MySQL有两个字符集概念:一个就是字符集本身,一个是字符集校验规则。字符集影响数据在传输和存储过程中的处理方式,而字符集校验则影响ORDER BY和GROUP BY这些排序方式。
1. 和存储有关的
character_set_server: 服务器字符集,服务器安装时指定的默认字符集设定。
character_set_database: 库字符集,数据库服务器中某个库使用的字符集设定,如果建库时没有指明,将使用服务器安装时指定的字符集设置。
character_system: 数据库系统使用的字符集设定。
在创建一个表的时候,每个字段只要不是binary,都会有一个字符集。如果不指定,那么在SHOW CREATE TABLE的时候,它是不会显示出来的。、
2. 和传输有关的
character_set_connection: 连接数据库的字符集设置类型,如果没有指明连接数据库使用的字符集类型就按照服务器端默认的字符设置
character_set_results: 数据库给客户端返回时使用的字符集设定,如果没有指明,使用服务器默认的字符集
character_set_client: 客户端使用的字符集,客户端发送过来文字的字符集
通常的使用中,character_set_client,character_set_connection这两个变量的值是一样的,也就是说查询不需 要进行编码转换。这样看来变量character_set_connection有些多余。当查询进入时,查询会被服务器从 character_set_client转换到character_set_connection,当查询执行时,查询会被服务器从 character_set_connection转换到列字符集。查询反回时,数据直接被服务器从列字符集转换到 character_set_results。很显然查询进入比查询返回多经历了一次转换
3.字符集的校对规则
字符集的校对规则设定分别由上面的character_set_connection, character_set_database, character_set_server决定
collation_connection: 连接字符集的校对规则
collation_database: 默认数据库使用的校对规则。当默认数据库改变时服务器则设置该变量。如果没有默认数据库,变量的值采用collation_server的值
collation_server: 服务器的默认校对规则
4. 字符集编码的关联规则
a、要保证数据库中存的数据与数据库编码一致,即数据编码与character_set_database一致;
b、要保证通讯的字符集与数据库的字符集一致,即character_set_client,character_set_connection与character_set_database一致;
c、要保证SELECT的返回与程序的编码一致,即character_set_results与程序编码一致;
d、要保证程序编码与浏览器编码一致,即程序编码与<meta http-equiv="Content-Type" content="text/html; charset=?"/>一致。


[size=large]附件:关于filter的具体设定[/size]
因为网络中字符在传递的时候,都是统一以iso-8859-1的编码传递,所以我们必须对request重新设定字符集,才能正常显示中文。如果采用filter类来实现,我们不用在每次取中文参数时都要重新设定。

filter类的内容:

/*
* ====================================================================
*
* javawebstudio 开源项目
*
* struts_db v0.1
*
* ====================================================================
*/
package com.strutslogin.util;

import java.io.ioexception;

import javax.servlet.filter;
import javax.servlet.filterchain;
import javax.servlet.filterconfig;
import javax.servlet.servletexception;
import javax.servlet.servletrequest;
import javax.servlet.servletresponse;

/**
* 中文过滤器
*/
public class setcharacterencodingfilter implements filter {

// ----------------------------------------------------- instance variables

/**
* the default character encoding to set for requests that pass through
* this filter.
*/
protected string encoding = null;

/**
* the filter configuration object we are associated with. if this value
* is null, this filter instance is not currently configured.
*/
protected filterconfig filterconfig = null;

/**
* should a character encoding specified by the client be ignored?
*/
protected boolean ignore = true;

// --------------------------------------------------------- public methods

/**
* take this filter out of service.
*/
public void destroy() {

this.encoding = null;
this.filterconfig = null;

}

/**
* select and set (if specified) the character encoding to be used to
* interpret request parameters for this request.
*
* @param request the servlet request we are processing
* @param result the servlet response we are creating
* @param chain the filter chain we are processing
*
* @exception ioexception if an input/output error occurs
* @exception servletexception if a servlet error occurs
*/
public void dofilter(servletrequest request, servletresponse response,
filterchain chain)
throws ioexception, servletexception {

// conditionally select and set the character encoding to be used
if (ignore || (request.getcharacterencoding() == null)) {
string encoding = selectencoding(request);
if (encoding != null)
request.setcharacterencoding(encoding);
}

// pass control on to the next filter
chain.dofilter(request, response);

}

/**
* place this filter into service.
*
* @param filterconfig the filter configuration object
*/
public void init(filterconfig filterconfig) throws servletexception {

this.filterconfig = filterconfig;
this.encoding = filterconfig.getinitparameter("encoding");
string value = filterconfig.getinitparameter("ignore");
if (value == null)
this.ignore = true;
else if (value.equalsignorecase("true"))
this.ignore = true;
else if (value.equalsignorecase("yes"))
this.ignore = true;
else
this.ignore = false;

}

// ------------------------------------------------------ protected methods

/**
* select an appropriate character encoding to be used, based on the
* characteristics of the current request and/or filter initialization
* parameters. if no character encoding should be set, return
* <code>null</code>.
* <p>
* the default implementation unconditionally returns the value configured
* by the <strong>encoding</strong> initialization parameter for this
* filter.
*
* @param request the servlet request we are processing
*/
protected string selectencoding(servletrequest request) {

return (this.encoding);

}

}//eoc


该代码来自于www.javawebstudio.com,特此感谢!

然后我们在web.xml中加一些配置,就可以了,配置如下:

<filter>
<filter-name>set character encoding</filter-name>
<filter-class>javawebstudio.struts_db.setcharacterencodingfilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>gbk</param-value>
</init-param>
<init-param>
<param-name>ignore</param-name>
<param-value>true</param-value>
</init-param>
</filter>

<filter-mapping>
<filter-name>set character encoding</filter-name>
<servlet-name>action</servlet-name>
</filter-mapping>

放在web.xml的合适位置。一般在最后,<jsp-config>标签之前(如果有的话)

经过以上步骤,jsp和mysql的中文显示及插入就都正常了。在struts中也正常。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值