Как скопировать или клонировать базу данных MySQL?

База данных
В MySQL можно создать резервную копию данных, создав их клон или копию, поэтому в случае любой неудачи их можно будет получить из своего клона. Для новых пользователей MySQL это популярный инструмент управления базами данных для реляционных баз данных (SQL); он управляет данными, размещая их в таблицах, которые не только помогают разработчикам легко управлять ими в хорошо структурированном виде, но также улучшают обработку компьютера, на котором они работают.
Чтобы создать резервную копию базы данных в MySQL, мы сделаем клон или копию с помощью очень простой процедуры, которая будет подробно обсуждаться в этой статье.
Как скопировать или клонировать базу данных MySQL
Чтобы понять создание клона базы данных в MySQL, мы рассмотрим пример названной базы данных; Linuxhint. Чтобы получить список всех используемых баз данных:

Мы будем использовать базу данных; Linuxhint:
Для отображения таблиц базы данных Linuxhint используйте команду:

Чтобы сделать резервную копию базы данных «Linuxhint», включая все ее таблицы, мы используем утилиту командной строки резервного копирования, известную как mysqldump. Прежде чем приступить к резервному копированию базы данных, позвольте нам немного кратко рассказать о mysqldump.
Что такое команда mysqldump
Команда mysqldump используется для создания и восстановления резервной копии базы данных MySQL и общего синтаксиса ее использования:
- Используйте предложение mysqldump для создания резервной копии базы данных
- Используйте флаг -u с именем пользователя для подключения к серверу MySQL.
- Также используйте флаг -p для пароля пользователя
- Замените базу данных именем базы данных, которую вы хотите клонировать.
- Используйте знак «>», чтобы создать резервную копию.
- Назначьте путь, а также предложите имя для клонирования файла с расширением.sql
Переходя к клону «Linuxhint», мы сначала создадим другую базу данных для резервного копирования данных базы данных Linuxhint в ней с именем Linuxhint_backup:
Чтобы проверить создание базы данных, выполните команду:
Новая база данных создана, выйдите из сервера MySQL с помощью команды:
Мы создадим в домашнем каталоге sql-файл с именем Linuxhint.sql и экспортируем все объекты базы данных Linuxhint в файл Linuxhint.sql с помощью утилиты mysqldump:
В приведенных выше выходных данных утилита mysqldump обращается к базе данных «Linuxhint» и запрашивает пароль базы данных и предоставляет его. После этого импортируйте данные файла «Linuxhint.sql» в «Linuxhint_backup» с помощью команды:
Данные были успешно скопированы, чтобы убедиться в этом, мы откроем сервер MySQL с помощью команды:
Отобразите базы данных, используя команду:
Чтобы использовать Linuxhint_backup, выполните команду:
Отобразите таблицы, используя команду:
Видно, что все данные из базы данных «Linuxhint» были успешно скопированы в Linuxhint_backup.
Вывод
Данные могут быть потеряны либо из-за сбоя сервера, либо из-за халатности пользователя, поэтому на всякий случай лучше иметь резервную копию. В MySQL резервную копию баз данных можно создать с помощью простого метода, который заключается в использовании утилиты резервного копирования mysqldump. В MySQL создается новая пустая база данных, затем с помощью утилиты mysqldump создается sql-файл в любом месте компьютера, где все данные экспортируются, а затем эти данные снова копируются во вновь созданную базу данных с помощью утилиты mysqldump. Таким образом, вы можете создать клон любой базы данных MySQL.
MySQL: Cloning a MySQL database on the same MySql instance
I would like to write a script which copies my current database sitedb1 to sitedb2 on the same mysql database instance. I know I can dump the sitedb1 to a sql script:
and then import it to sitedb2 . Is there an easier way, without dumping the first database to a sql file?
![]()
16 Answers 16
As the manual says in Copying Databases you can pipe the dump directly into the mysql client:
If you’re using MyISAM you could copy the files, but I wouldn’t recommend it. It’s a bit dodgy.
Integrated from various good other answers
Both mysqldump and mysql commands accept options for setting connection details (and much more), like:
Also, if the new database is not existing yet, you have to create it beforehand (e.g. with echo «create database new_db_name» | mysql -u <dbuser> -p ).
Using MySQL Utilities
The MySQL Utilities contain the nice tool mysqldbcopy which by default copies a DB including all related objects (“tables, views, triggers, events, procedures, functions, and database-level grants”) and data from one DB server to the same or to another DB server. There are lots of options available to customize what is actually copied.
So, to answer the OP’s question:
Best and easy way is to enter these commands in your terminal and set permissions to the root user. Works for me.
You could use (in pseudocode):
The reason I’m not using the CREATE TABLE . SELECT . syntax is to preserve indices. Of course this only copies tables. Views and procedures are not copied, although it can be done in the same manner.
You need to run the command from terminal / command prompt.
e.g: mysqldump -u root test_db1 | mysql -u root test_db2
This copies test_db1 to test_db2 and grant the access to ‘root’@’localhost’
![]()
First create the duplicate database:
Make sure the permissions etc are all in place and:
![]()
A simple way to do so if you installed phpmyadmin :
Go to your database, select "operation" tab, and you can see the "copy database to" block. Use it and you can copy the database.
![]()
As mentioned in Greg’s answer, mysqldump db_name | mysql new_db_name is the free, safe, and easy way to transfer data between databases. However, it’s also really slow.
If you’re looking to backup data, can’t afford to lose data (in this or other databases), or are using tables other than innodb , then you should use mysqldump .
If you’re looking for something for development, have all of your databases backed up elsewhere, and are comfortable purging and reinstalling mysql (possibly manually) when everything goes wrong, then I might just have the solution for you.
I couldn’t find a good alternative, so I built a script to do it myself. I spent a lot of time getting this to work the first time and it honestly terrifies me a little to make changes to it now. Innodb databases were not meant to copied and pasted like this. Small changes cause this to fail in magnificent ways. I haven’t had a problem since I finalized the code, but that doesn’t mean you won’t.
Systems tested on (but may still fail on):
- Ubuntu 16.04, default mysql, innodb, separate files per table
- Ubuntu 18.04, default mysql, innodb, separate files per table
We’ve since switched to docker and a simple copy of the entire mysql data folder, so this script is no longer maintained. Leaving it in case it’s able to help anyone in the future.
What it does
- Gets sudo privilege and verifies you have enough storage space to clone the database
- Gets root mysql privileges
- Creates a new database named after the current git branch
- Clones structure to new database
- Switches into recovery mode for innodb
- Deletes default data in new database
- Stops mysql
- Clones data to new database
- Starts mysql
- Links imported data in new database
- Switches out of recovery mode for innodb
- Restarts mysql
- Gives mysql user access to database
- Cleans up temporary files
How it compares with mysqldump
On a 3gb database, using mysqldump and mysql would take 40-50 minutes on my machine. Using this method, the same process would only take
How we used it
We had our SQL changes saved alongside our code and the upgrade process is automated on both production and development, with each set of changes making a backup of the database to restore if there’s errors. One problem we ran into was when we were working on a long term project with database changes, and had to switch branches in the middle of it to fix a bug or three.
In the past, we used a single database for all branches, and would have to rebuild the database whenever we switched to a branch that wasn’t compatible with the new database changes. And when we switched back, we’d have to run the upgrades again.
We tried mysqldump to duplicate the database for different branches, but the wait time was too long (40-50 minutes), and we couldn’t do anything else in the meantime.
This solution shortened the database clone time to 1/5 the time (think coffee and bathroom break instead of a long lunch).
Common tasks and their time
Switching between branches with incompatible database changes takes 50+ minutes on a single database, but no time at all after the initial setup time with mysqldump or this code. This code just happens to be
5 times faster than mysqldump .
Here are some common tasks and roughly how long they would take with each method:
Create feature branch with database changes and merge immediately:
- Single database:
Create feature branch with database changes, switch to main for a bugfix, make an edit on the feature branch, and merge:
- Single database:
Create feature branch with database changes, switch to main for a bugfix 5 times while making edits on the feature branch inbetween, and merge:
- Single database:
The code
Do not use this unless you’ve read and understood everything above. It is no longer maintained, so it is more and more likely to be broken as time goes on.