Mysql中脚本示例
Mysql中脚本示例
一、修改数据库编码及字符集(比较简单,在可视化工具中直接改了,也可以使用如下命令)
– 可直接复制运行
ALTER DATABASE db_name CHARACTER SET = utf8mb4 COLLATE = utf8mb4_bin;
– 参数解释:
– db_name 数据库名;
– utf8mb4 改后的字符集
– utf8mb4_bin 改后的排序规则
二、批量修改某一数据库中,所有的表和表中的字段的编码和排序规则
2.1、第一步生成修改语句
– 第一步,先生成修改的SQL语句
USE testboot;
SELECT
CONCAT( 'ALTER TABLE ', TABLE_SCHEMA, '.', TABLE_NAME, ' MODIFY COLUMN ', COLUMN_NAME,
' ', COLUMN_TYPE, ' CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci;' )
FROM
information_schema.`COLUMNS`
WHERE
COLLATION_NAME RLIKE 'utf8mb4_general_ci'
AND TABLE_SCHEMA = 'testboot';
-- 参数解释
-- testboot 你要修改的数据库
-- utf8mb4 改后的编码
-- 第一个 utf8mb4_general_ci 改后的排序规则
-- 第二个 utf8mb4_general_ci 要改的表的现在的排序规则,这里本来是utf8mb4_bin,我改过的,用utf8mb4_bin,会返回空
-- testboot 你要修改的数据库
类似这种
ALTER TABLE testboot.address MODIFY COLUMN address varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci;
ALTER TABLE testboot.address MODIFY COLUMN city varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci;
ALTER TABLE testboot.address MODIFY COLUMN province varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci;
ALTER TABLE testboot.blog MODIFY COLUMN content longtext CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci;
ALTER TABLE testboot.blog MODIFY COLUMN description varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci;
ALTER TABLE testboot.blog MODIFY COLUMN summary varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci;
ALTER TABLE testboot.blog MODIFY COLUMN tags varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci;
ALTER TABLE testboot.blog MODIFY COLUMN title varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci;
ALTER TABLE testboot.navigation MODIFY COLUMN name varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci;
ALTER TABLE testboot.navigation MODIFY COLUMN path varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci;
ALTER TABLE testboot.user MODIFY COLUMN email varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci;
ALTER TABLE testboot.user MODIFY COLUMN name varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci;
ALTER TABLE testboot.user MODIFY COLUMN password varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci;
ALTER TABLE testboot.user MODIFY COLUMN tel varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci;
2.2、第二步,复制语句,执行就可以了(注意会初始化字段的注释,字段长度)
修改完毕;可查看。
三、添加外键和约束
思考:约束和索引
3.1、无别名
alter table table_name add unique (comlun_name);
3.2、有别名
ALTER TABLE pis_role
ADD CONSTRAINT ‘UK_72j9ge2wxs4j81mpvfjak1krc’ UNIQUE ( role_name
);
四、批量删除某一数据库中所有表
SELECT CONCAT('DROP TABLE ', table_name,';') FROM information_schema.`TABLES` WHERE table_schema='dbName';