MySQL修改数据库名称
MySQL修改数据库名称比较麻烦,不支持直接修改,需要通过其他方式间接达到修改数据库名称的目的,整理了一下,大致有如下几种方式。
方法一:通过修改表名称,间接实现修改数据库名称(推荐)
比如数据库名称db_old 想改名为 db_new。
(1)先创建新库:
create database db_new;
(2)修改表名,将表移动到新库里:
rename table db_old.tb to db_new.tb;
如果库里有很多表,就要写一个脚本,批量执行。
(3)最后删除旧库:
drop database db_old;
附上一个shell脚本批量修改表名称。
#!/bin/bash
1. 假设将db_old数据库名改为db_new
mysql -h127.0.0.1 -uadmin -p'123456' -e 'create database if not exists db_new'
list_table=$(mysql -h127.0.0.1 -uadmin -p'123456' -Nse "select table_name from information_schema.TABLES where TABLE_SCHEMA='db_old'")
for table in $list_table
do
mysql -h127.0.0.1 -uadmin -p'123456' -e "rename table db_old.$table to db_new.$table"
done