修改MySQL 数据库名称

编程知识 行业动态 更新时间:2024-06-13 00:19:27

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 数据库名称

本文发布于:2023-03-28 08:52:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/e6be57eec54653b53e8095eea45dc63e.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:名称   数据库   MySQL

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!