MySQL修改数据库、表、列、外键字符编码和排序编码

时间:2022-11-05 07:23:26

在重启Confluence应用时,突然遇见这个检查错误,查询总结需要修改Mysql数据库的所有字符编码和排序编码,报错如下:

    Confluence Help – This installation of Confluence has failed one or more bootstrap configuration checks. Please check the logs for details.

修改数据库、表、列、外键字符编码和排序编码

设置数据库字符编码为utf8,排序编码utf8_bin

SET FOREIGN_KEY_CHECKS=0;
ALTER DATABASE db_name CHARACTER SET utf8 COLLATE utf8_bin;
SET FOREIGN_KEY_CHECKS=1;

设置表字符编码,将查询将生成一条条ALTER TABLE语句,执行所有查询结果

SET FOREIGN_KEY_CHECKS=0;
SELECT CONCAT('ALTER TABLE ', table_name, ' CHARACTER SET utf8 COLLATE utf8_bin;') FROM information_schema.TABLES AS T, information_schema.`COLLATION_CHARACTER_SET_APPLICABILITY` AS C WHERE C.collation_name = T.table_collation AND T.table_schema = 'db_name' AND ( C.CHARACTER_SET_NAME != 'utf8' OR C.COLLATION_NAME != 'utf8_bin' );
SET FOREIGN_KEY_CHECKS=1;

设置列字符编码,将查询生成一条条ALTER TABLE语句,执行所有查询结果

SET FOREIGN_KEY_CHECKS=0;
SELECT CONCAT('ALTER TABLE `', table_name, '` MODIFY `', column_name, '` ', DATA_TYPE, '(', CHARACTER_MAXIMUM_LENGTH, ') CHARACTER SET UTF8 COLLATE utf8_bin', (CASE WHEN IS_NULLABLE = 'NO' THEN ' NOT NULL' ELSE '' END), ';') FROM information_schema.COLUMNS WHERE TABLE_SCHEMA = 'yourDB' AND DATA_TYPE = 'varchar' AND ( CHARACTER_SET_NAME != 'utf8' OR COLLATION_NAME != 'utf8_bin' );
SET FOREIGN_KEY_CHECKS=1;

或者

SET FOREIGN_KEY_CHECKS=0;
SELECT CONCAT('ALTER TABLE `', table_name, '` MODIFY `', column_name, '` ', DATA_TYPE, ' CHARACTER SET UTF8 COLLATE utf8_bin', (CASE WHEN IS_NULLABLE = 'NO' THEN ' NOT NULL' ELSE '' END), ';') FROM information_schema.COLUMNS WHERE TABLE_SCHEMA = 'yourDB' AND DATA_TYPE != 'varchar' AND ( CHARACTER_SET_NAME != 'utf8' OR COLLATION_NAME != 'utf8_bin' );
SET FOREIGN_KEY_CHECKS=1;

忽略外键约束
可能需要忽略外键约束。可以SET FOREIGN_KEY_CHECKS在更新数据库时使用该命令忽略外键约束。

  SET FOREIGN_KEY_CHECKS=0;
  --其他查询语句
  SET FOREIGN_KEY_CHECKS=1;

备注:
作者:Shengming Zeng
博客:http://www.cnblogs.com/zengming/
严正声明:
1.由于本博客部分资源来自互联网,版权均归原作者所有。转载的目的是用于学术交流与讨论学习,将不对任何资源负法律责任。
2.若无意中侵犯到您的版权利益,请来信联系我,我会在收到信息后会尽快给予处理!
3.所有资源内容仅供学习交流之用,请勿用作商业用途,谢谢。
4.如有转发请注明出处,来源于http://www.cnblogs.com/zengming/,谢谢合作。