Mysql设置字符编码的方法


  本文标签:Mysql设置字符

  Mysql设置字符编码可以解决一些常见的问题,比如使用不同的字符集出错的问题,下面就是Mysql设置字符编码解决该问题的具体介绍  。

  错误是在你的结果集中有两种字符集  。   

  比如说你在两个表联合查询,一个表的字符集是latin1,另一个是utf8,
这样在你的结果集中有两种字符集,mysql会报错误  。   

  一个表中不同的字段使用不同的字符集,也是一个道理  。   

  用SHOW   CREATE   TABLE   table_name;可以看出具体的字符集设置  。

  查了帮助手册,说是user的字符集没有设,默认为utf8,将其转为latin1或gb2312等字符集

  解决方法:  

  将不同的字符集,转化成统一的字符集  。  下面就是Mysql设置字符编码的方法  。

  1. After   an   upgrade   to   MySQL   4.1,   the   statement   fails:       
  2.  
  3. mysql>   SELECT   SUBSTRING_INDEX(USER(),@,1);     
  4.  
  5. ERROR   1267   (HY000):   Illegal   mix   of   collations     
  6.  
  7. (utf8_general_ci,IMPLICIT)   and   (latin1_swedish_ci,COERCIBLE)     
  8.  
  9. for   operation   substr_index     
  10.  
  11. The   reason   this   occurs   is   that   usernames   are   stored   using   UTF8   (see   section   11.6   UTF8   for   Metadata).   As   a   result,   the   USER()   function   and   the   literal   string   @   have   different   character   sets   (and   thus   different   collations):       
  12.  
  13. mysql>   SELECT   COLLATION(USER()),   COLLATION(@);     
  14.  
  15. +-------------------+-------------------+     
  16.  
  17. |   COLLATION(USER())   |   COLLATION(@)         |     
  18.  
  19. +-------------------+-------------------+     
  20.  
  21. |   utf8_general_ci       |   latin1_swedish_ci   |     
  22.  
  23. +-------------------+-------------------+     
  24.  
  25. One   way   to   deal   with   this   is   to   tell   MySQL   to   interpret   the   literal   string   as   utf8:       
  26.  
  27. mysql>   SELECT   SUBSTRING_INDEX(USER(),_utf8@,1);     
  28.  
  29. +------------------------------------+     
  30.  
  31. |   SUBSTRING_INDEX(USER(),_utf8@,1)   |     
  32.  
  33. +------------------------------------+     
  34.  
  35. |   root                                                               |     
  36.  
  37. +------------------------------------+     
  38.  
  39. Another   way   is   to   change   the   connection   character   set   and   collation   to   utf8.   You   can   do   that   with   SET   NAMES   utf8   or   by   setting   the   character_set_connection   and   collation_connection   system   variables   directly.       

  表的编码转换可以用:(MySQL   Version   >   4.12)

  1. ALTER   TABLE   tbl_name   CONVERT   TO   CHARACTER   SET   charset_name;    

  之前的版本可以用:  

  1. ALTER   TABLE   tbl_name   CHARACTER   SET   charset_name;