MySQL编码问题集合

1.以root用户的身份登录,查看编码设置

mysql> SHOW VARIABLES LIKE 'character%';

 

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

 

character_set_client为客户端编码方式

character_set_connection为建立的连接使用的编码

character_set_database数据库的编码

 

character_set_results结果集的编码;

character_set_server数据库服务器的编码;

只要保证以上四个采用的编码方式一样,就不会出现乱码问题

 

另外,另一个查看数据库编码的命令

mysql> SHOW VARIABLES LIKE 'collation_%';


+----------------------+-------------------+
| Variable_name | Value |
+----------------------+-------------------+
| collation_connection | latin1_swedish_ci |
| collation_database | latin1_swedish_ci |
| collation_server | latin1_swedish_ci |
+----------------------+-------------------+

 

 

2.以root用户的身份登录,设置编码:

mysql>

  set character_set_client = utf8;
  set character_set_server = utf8;
  set character_set_connection = utf8;
  set character_set_database = utf8;
  set character_set_results = utf8;
  set collation_connection = utf8_general_ci;
  set collation_database = utf8_general_ci;
  set collation_server = utf8_general_ci;
以上命令有部分只对当前登录有效

 

3.以root用户的身份登录,新建数据库,导入sql的情况:

  3.1 导入sql脚本文件前,先确保该脚本文件及内容格式为UTF-8编码格式,
  3.2 mysql> use [库名] 进入相应数据库
  3.3 mysql> set names utf8;
  3.4 mysql> source [脚本文件URI];

 

4.以root用户的身份登录,修改数据库、表、字段的编码:

  mysql> alter database [database name] character set utf8;

  mysql> alter table [table name] character set utf8;

  mysql> alter table [table name] modify [column name, for example: user_name] [type, for example: varchar(50)] CHARACTER SET utf8;

 

5.写数据库链接程序的时候,为DB_URL添加参数:

  例如JDBC,final String DB_URL = "jdbc:mysql://127.0.1:3306/[database_name]?useUnicode=true&characterEncoding=utf-8";

 

6.修改MySQL配置文件参数

  在windows7中,my.ini配置文件位于C:\ProgramData\MySQL\MySQL Server 5.6

  在Linux下一般是 /etc/my.cnf

  --在 [mysqld] 标签下加上三行
    default-character-set = utf8
    character_set_server = utf8

    init_connect='SET NAMES utf8' (设定连接mysql数据库时使用utf8编码,以让mysql数据库为utf8运行) 

    lower_case_table_names = 1 //表名不区分大小写(此与编码无关)

  --在 [mysql] 标签下加上一行
    default-character-set = utf8 

  --在 [mysql.server]标签下加上一行
    default-character-set = utf8

  --在 [mysqld_safe]标签下加上一行
    default-character-set = utf8

  --在 [client]标签下加上一行
    default-character-set = utf8

posted @ 2013-12-29 19:43  rldts  阅读(390)  评论(0编辑  收藏  举报