MySQL不支持直接修改数据库名称语法。

那么要修改数据库名称该如何操作呢?例如,我们将数据库test 修改为test2。

第一步 创建新名称对应的数据库

create database if not exists test2

第二步 获取所有源库的表,即test数据库下所有表。

select table_name from information_schema.tables where table_schema='test'

第三步 通过rename语法修改表schema信息

rename table test.[table_name] to test2.[table_name]

修改完成所有表后,删除原有数据库test

drop database if exists test

优化整理之后Shell脚本

创建 move_mysql_database.sh

chmod +755 move_mysql_database.sh

#!/bin/bash

olddb=''
newdb=''
if [ $1 ]; then
   echo "oldDB is $1"
   olddb=$1
else
   echo "oldDb is empty"
   exit 0;
fi

if [ $2 ]; then
   echo "new db is $2"
   newdb=$2
else
   echo "new db is empty"
   exit 0;
fi

echo "move database $olddb to $newdb "

my_connect="mysql -h 192.168.0.114 -P3306 -u root -pPassword@123"
echo "$my_connect"

$my_connect -e "create database if not exists $newdb"

list_table=$( $my_connect -Nse "select table_name from information_schema.tables where table_schema='$olddb'" )

echo "start to move $olddb tables ... "
for table in $list_table
do
   $my_connect -e "rename table $olddb.$table to $newdb.$table"
done

echo "move $olddb tables finished "
echo "drop database $olddb ..."
$my_connect -e "drop database if exists $olddb"

echo "move success"

 执行修改脚本

sh move_mysql_database.sh test test2

备注:move_mysql_database.sh 中 my_connect 变量需要修改为自己的mysql链接信息

my_connect="mysql -h 192.168.0.114 -P3306 -u root -pPassword@123"

更多推荐

修改MySQL 数据库名称