(1) 最简单的修改方法,就是修改mysql的my.ini文件中的字符集键值, 如 default-character-set = utf8 character_set_server = utf8 修改完后,重启mysql的服务,service mysql restart 使用 mysql SHOW VARIABLES LIKE 'character%';查看,发现数据库编码均
(1) 最简单的修改方法,就是修改mysql的my.ini文件中的字符集键值,
如 default-character-set = utf8
character_set_server = utf8
修改完后,重启mysql的服务,service mysql restart
使用 mysql> SHOW VARIABLES LIKE 'character%';查看,发现数据库编码均已改成utf8
<ol> <li><span>+--------------------------+---------------------------------+ </span></li> <li><span>| Variable_name | Value | </span></li> <li><span>+--------------------------+---------------------------------+ </span></li> <li><span>| character_set_client | utf8 | </span></li> <li><span>| character_set_connection | utf8 | </span></li> <li><span>| character_set_database | utf8 | </span></li> <li><span>| character_set_filesystem | binary | </span></li> <li><span>| character_set_results | utf8 | </span></li> <li><span>| character_set_server | utf8 | </span></li> <li><span>| character_set_system | utf8 | </span></li> <li><span>| character_sets_dir | D:"mysql-5.0.37"share"charsets" | </span></li> <li><span>+--------------------------+---------------------------------+ </span></li> </ol>
(2) 还有一种修改mysql默认字符集的方法,就是使用mysql的命令
<ol> <li><span><span>mysql</span><span>></span><span> SET </span><span>character_set_client</span><span> = </span><span>utf8</span><span> ; </span></span></li> <li> <span>mysql</span><span>></span><span> SET </span><span>character_set_connection</span><span> = </span><span>utf8</span><span> ; </span> </li> <li> <span>mysql</span><span>></span><span> SET </span><span>character_set_database</span><span> = </span><span>utf8</span><span> ; </span> </li> <li> <span>mysql</span><span>></span><span> SET </span><span>character_set_results</span><span> = </span><span>utf8</span><span> ; </span> </li> <li> <span>mysql</span><span>></span><span> SET </span><span>character_set_server</span><span> = </span><span>utf8</span><span> ; </span> </li> <li><span> </span></li> <li> <span>mysql</span><span>></span><span> SET </span><span>collation_connection</span><span> = </span><span>utf8</span><span> ; </span> </li> <li> <span>mysql</span><span>></span><span> SET </span><span>collation_database</span><span> = </span><span>utf8</span><span> ; </span> </li> <li> <span>mysql</span><span>></span><span> SET </span><span>collation_server</span><span> = </span><span>utf8</span><span> ; </span> </li> </ol>
一般就算设置了表的mysql默认字符集为utf8并且通过UTF-8编码发送查询,你会发现存入数据库的仍然是乱码。问题就出在这个connection连接层上。解决方法是在发送查询前执行一下下面这句:
<ol><li><span>SET NAMES 'utf8'; </span></li></ol>
它相当于下面的三句指令:
<ol> <li><span><span>SET </span><span>character_set_client</span><span> = </span><span>utf8</span><span>; </span></span></li> <li> <span>SET </span><span>character_set_results</span><span> = </span><span>utf8</span><span>; </span> </li> <li> <span>SET </span><span>character_set_connection</span><span> = </span><span>utf8</span><span>; </span> </li> </ol>