Restore mysql database with different name

You can let mysqldump create the dump in such a way that it does not create or select the database.

EXAMPLE : You are dumping the database db1 and loading it into database db2

This will put in the CREATE DATABASE and the USE commands in the dump

mysqldump -u... -p... --routines --triggers --databases db1 > /root/db1.sql

This will not put in the CREATE DATABASE and the USE commands in the dump (this is what you want)

mysqldump -u... -p... --routines --triggers db1 > /root/db1.sql

You can load it into another database (such as db2) in one of four(4) ways:

OPTION 1

$ mysqldump -u... -p... --routines --triggers db1 | mysql -u... -p... -A -Ddb2

OPTION 2

$ mysqldump -u... -p... --routines --triggers db1 > /root/db1.sql
$ mysql -u... -p... -A -Ddb2 < /root/db1.sql

OPTION 3

$ mysqldump -u... -p... --routines --triggers db1 > /root/db1.sql
$ mysql -u... -p... -A -Ddb2
mysql> source /root/db1.sql

OPTION 4

$ mysqldump -u... -p... --routines --triggers db1 > /root/db1.sql
$ mysql -u... -p... -A
mysql> use db2
mysql> source /root/db1.sql

Give it a Try !!!


I am a big fan of dump, edit and insert. but you do not have to open the text file (dump file) to change it (this is especially usefull when it is several milion lines long). if you want to dump the database MYDATABASE.

mysqldump MYDATABASE > mydump.sql

then use sed to replace the old database name with new one like this

sed -i 's/MYDATABASE/MYNEWDATABASE/g' mydump.sql

then you can simply create the new database and import it again, and it will create all tables with in the new databae MYNEWDATABASE'

mysqladmin create MYNEWDATABASE

mysql MYNEWDATABASE < mydump.sql

Edit: Like some nice people in the comments section have pointed out, this can be dangerous, if some of the data is also changed by this above, so, to conctrete ways to avoid this is.

1) Grep for this in the dump, before you change it, like this.

cat mydump.sql | grep "MYDATABASE"

and

2) we can add some ` to make it safer like this:

sed -i 's/`MYDATABASE`/`MYNEWDATABASE`/g' mydump.sql

if anyone else have concrete suggestions, I am happy to edit my answer in another 4 years.


I have done this once, long time ago.

When you export all your data, there is an option to set the database name in the begining of the file, something as: "use database x"

So, you can change this declaration.