MySQL数据库改名的两种实用方法

如果表示MyISAM那么可以直接去到数据库目录mv就可以。

Innodb完全不行,会提示相关表不存在。

第一种:

1.创建要改的新名称数据库test_new;

2.备份原名称数据库test_old数据;

mysqldump -uroot -p test_old > ./test_old.sql

3.导入备份数据到新数据库test_new中。

mysqld -uroot -p test_new < ./test_old.sql

4.看需要是否删除旧数据库

drop database test_old;

优点:安全,保证数据完整

缺点:如果数据量大,会很耗时间

第二种(推荐):

一个脚本搞定:

#!/bin/bash

source /etc/profile        #加载系统环境变量
source ~/.bash_profile    #加载用户环境变量
set -o nounset             #引用未初始化变量时退出

mysqlconn="mysql -h localhost -uroot -p123456"

#需要修改的数据库名
olddb="test_old"
#修改后的数据库名
newdb="test_new"

#创建新数据库
$mysqlconn -e "drop database if exists ${newdb};create database ${newdb};"

#获取所有表名
tables=$($mysqlconn -N -e "select table_name from information_schema.tables where table_schema='${olddb}'")

#修改表名
for name in $tables;do
    $mysqlconn -e "rename table ${olddb}.${name} to ${newdb}.${name}"
done

#删除老的空库
#$mysqlconn -e "drop database ${olddb}"

原理:这里用到了rename table,改表名的命令,如果新表名后面加数据库名,就会将老数据库的表移动到新的数据库,所以,这种方法即安全,又快速。

借鉴至:https://www.cnblogs.com/leffss/p/7832100.html

原文地址:https://www.cnblogs.com/dannylinux/p/13678654.html