mysql修改字符集

1.查看当前数据库字符集:

show VARIABLES like 'character%';

2.修改数据库字符集(ps:修改完数据库字符集,需要重启mysql数据库。):

alter database 数据库名 character set utf8mb4;

3.修改表字符集:

ALTER TABLE  表名 DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci;

生成所有表修改字符集语句:

SELECT TABLE_NAME,CONCAT('ALTER TABLE  ',TABLE_NAME,' DEFAULT CHARACTER SET ',a.DEFAULT_CHARACTER_SET_NAME,' COLLATE ',a.DEFAULT_COLLATION_NAME,';') executeSQL FROM information_schema.SCHEMATA a,information_schema.TABLES b
WHERE a.SCHEMA_NAME=b.TABLE_SCHEMA
AND a.DEFAULT_COLLATION_NAME!=b.TABLE_COLLATION
AND b.TABLE_SCHEMA='数据库名' 

4.修改列字符集

ALTER TABLE  表名 CHANGE  列名  列名  VARCHAR( 100 ) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL;

生成所有列修改字符集语句:

select b.table_name,b.column_name,b.character_set_name,b.collation_name
,CONCAT('ALTER TABLE ',b.table_name,' MODIFY ',b.column_name,' ',b.DATA_TYPE,'(',b.CHARACTER_MAXIMUM_LENGTH,') ',CASE WHEN b.COLUMN_DEFAULT IS NULL THEN ''  ELSE CONCAT('DEFAULT \'',b.COLUMN_DEFAULT,'\'') END,' COMMENT \'',b.COLUMN_COMMENT,'\';') executeSQL
 from information_schema.TABLES a,information_schema.COLUMNS b where  b.character_set_name IS NOT NULL and a.TABLE_SCHEMA=b.TABLE_SCHEMA AND a.TABLE_NAME=b.TABLE_NAME
AND a.TABLE_COLLATION!=b.COLLATION_NAME
and a.TABLE_SCHEMA='数据库名'

这些修改完之后,可能需要修改java程序与数据库的连接配置:

原来是这样的:String url = "jdbc:mysql://HOST:PORT/DATABASE?useUnicode=true&characterEncoding=UTF-8";
现在改为:String url = "jdbc:mysql://HOST:PORT/DATABASE?useUnicode=true&characterEncoding=utf8mb4";(服务无法启动,报错。。。。。。)

将连接配置修改为

String url = "jdbc:mysql://HOST:PORT/DATABASE?useUnicode=true";

并且修改数据库配置my.cnf

[client]
default-character-set = utf8mb4
[mysql]
default-character-set = utf8mb4
[mysqld]
character-set-client-handshake = FALSE
character-set-server = utf8mb4
collation-server = utf8mb4_unicode_ci

改完之后重启数据库

posted @ 2019-09-19 15:21  EasilyAi  阅读(26083)  评论(0编辑  收藏  举报