MySQL手册中有介绍。

通常我只是转储数据库并用一个新名称重新导入它。这不是非常大的数据库的一个选项。重命名数据库| SCHEMA} db_name TO new_db_name做坏事,只存在于少数版本中,总的来说是个坏主意。

这需要与InnoDB一起工作,InnoDB存储的东西与MyISAM非常不同。


当前回答

这里已经有很多非常好的答案,但我没有看到PHP版本。这将在大约一秒钟内复制一个800M DB。

$oldDbName = "oldDBName";
$newDbName = "newDBName";
$oldDB     = new mysqli("localhost", "user", "pass", $oldDbName);
if($oldDB->connect_errno){
    echo "Failed to connect to MySQL: (" . $oldDB->connect_errno . ") " . $oldDB->connect_error;
    exit;
}
$newDBQuery = "CREATE DATABASE IF NOT EXISTS {$newDbName}";
$oldDB->query($newDBQuery);
$newDB = new mysqli("localhost", "user", "pass");
if($newDB->connect_errno){
    echo "Failed to connect to MySQL: (" . $newDB->connect_errno . ") " . $newDB->connect_error;
    exit;
}

$tableQuery  = "SHOW TABLES";
$tableResult = $oldDB->query($tableQuery);
$renameQuery = "RENAME TABLE\n";
while($table = $tableResult->fetch_array()){
    $tableName = $table["Tables_in_{$oldDbName}"];
    $renameQuery .= "{$oldDbName}.{$tableName} TO {$newDbName}.{$tableName},";
}
$renameQuery = substr($renameQuery, 0, strlen($renameQuery) - 1);
$newDB->query($renameQuery);

其他回答

我认为这个解决方案更简单,是一些开发人员提出的。phpMyAdmin对此有一个操作。

从phpMyAdmin中选择要选择的数据库。在选项卡中有一个叫做Operations,转到rename部分。这是所有。

正如许多人建议的那样,它使用新名称创建一个新数据库,将旧数据库的所有表转储到新数据库中,并删除旧数据库。

更新2022-09-22:MySQL 8.0+增加了一个更简单的解决方案:

不知道从什么时候开始添加RENAME TO关键字,但肯定更简单。不过在尝试之前,我会先把桌子备份一下,尤其是如果你的桌子很大的话。无论如何,它可以实现如下:

ALTER TABLE `schema_name`.`table_name` 
RENAME TO  `schema_name`.`new_table_name` ;

为了便于阅读,我把它分成了两行,但也可以写成单行,如下:

ALTER TABLE `schema_name`.`table_name` RENAME TO `schema_name`.`new_table_name` ;

如果你更喜欢GUI工具,并且碰巧安装了MySQL Workbench,你可以使用内置的迁移向导

在MySQL管理员中执行以下操作:

在Catalogs下,创建一个新的数据库模式。 转到备份并创建的备份 旧的模式。 执行备份。 转到恢复并打开文件 在步骤3中创建。 在目标下选择“另一个模式” 模式并选择新的数据库 模式。 开始恢复。 验证新模式,如果看起来 很好,删除旧的。

I posted this How do I change the database name using MySQL? today after days of head scratching and hair pulling. The solution is quite simple export a schema to a .sql file and open the file and change the database/schema name in the sql CREAT TABLE section at the top. There are three instances or more and may not be at the top of the page if multible schemas are saved to the file. It is posible to edit the entire database this way but I expect that in large databases it could be quite a pain following all instances of a table property or index.

可以使用SQL生成SQL脚本,将源数据库中的每个表传输到目标数据库。

在运行该命令生成的脚本之前,必须先创建目标数据库。

您可以使用这两个脚本中的任何一个(我最初建议使用前者,有人“改进”了我的回答,使用GROUP_CONCAT。随你挑,但我更喜欢原版):

SELECT CONCAT('RENAME TABLE $1.', table_name, ' TO $2.', table_name, '; ')
FROM information_schema.TABLES 
WHERE table_schema='$1';

or

SELECT GROUP_CONCAT('RENAME TABLE $1.', table_name, ' TO $2.', table_name SEPARATOR '; ')
FROM information_schema.TABLES 
WHERE table_schema='$1';

($1和$2分别是源和目标)

这将生成一个SQL命令,然后必须运行该命令。

注意,GROUP_CONCAT有一个默认的长度限制,对于包含大量表的数据库可能会超过这个长度限制。您可以通过执行SET SESSION group_concat_max_len = 100000000来更改该限制;(或其他较大的数字)。