MySQL手册中有介绍。

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

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


当前回答

下面是一行Bash代码片段,用于将所有表从一个模式移动到另一个模式:

history -d $((HISTCMD-1)) && mysql -udb_user -p'db_password' -Dold_schema -ABNnqre'SHOW TABLES;' | sed -e's/.*/RENAME TABLE old_schema.`&` TO new_schema.`&`;/' | mysql -udb_user -p'db_password' -Dnew_schema

开始时的history命令只是确保包含密码的MySQL命令不会保存到shell历史记录中。

确保db_user对旧模式具有读/写/删除权限,对新模式具有读/写/创建权限。

其他回答

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

步骤:

点击http://localhost/phpmyadmin/ 选择您的数据库 点击操作选项卡 将有一个选项卡作为“重命名数据库到”。添加新名称并勾选调整权限。 点击Go。

这里已经有很多非常好的答案,但我没有看到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);

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.

我提出了一个关于服务器故障的问题,试图在使用MySQL代理恢复非常大的数据库时解决停机时间。我没有取得任何成功,但我最终意识到我想要的是RENAME DATABASE功能,因为由于数据库的大小,转储/导入不是一个选项。

MySQL有一个内置的RENAME TABLE功能,所以我最终写了一个简单的Python脚本来为我做这项工作。我把它发布在GitHub上,以防它对其他人有用。