开发者

Force a new database name on import with mysql and php

I have a large database dump.sql file I am importing from the command line in linux. The .sql dump creates a database named "database_name". I want to import the database from this .sql file but I want to force it to a database with a different name, as the script currently overwrites "database_name" and "database_name" already exists and has data I can't overwri开发者_Go百科te.

Is the best option to find and replace within the .sql file? What is the best method for that since the file is 50mb. I can't simply file_get_contents() on that shiz? Can I?

Below are the lines I would have to replace in the .sql file:

CREATE DATABASE /*!32312 IF NOT EXISTS*/ `database_name` /*!40100 DEFAULT CHARACTER SET latin1 */;
USE `database_name`;


When dumping the database with mysqldump, use the option --no-create-db. This will suspress the CREATE DATABASE statement in your dump file.
Then restore the database with
mysql -h <host> -u <user> -p <databaseName> < dump.sql
In this way you can restore your data in whatever database you like (But that database has to exist!)


You have to replace the database_name in the .sql file.

You can do that from the shell with sed 's/database_name/new_database_name/' dumpFile.sql > newDumpFile.sql

this is the correct answer to my question but was provided by 'fab' in the comments of another answer.

NOTE: As @Diego pointed out in the comments, if the string 'database_name' shows up anywhere else in this .sql dump, it will be replaced there as well. You may want to view the contents of the .sql file using less file_name.sql and then be more explicit with your find/replace.


The only reliable way is to open the file, find the following line (about 10 to 15 lines from start):

CREATE DATABASE /!32312 IF NOT EXISTS/ old_database_name ...

USE old_database_name;

and replace old_database_name with the new name in both places. I just did this on a 5.9 GB file with vim. It took about 15 sec. to open the file, 3 sec. to edit the line and 30 sec. to save the file. Not sure any other text editor allows you do do this!


This is an old question but I was faced with the exact same problem today. Here is how I solved it:

pv 20171212.dump.bz2 | bunzip2 | sed -e '/^\(CREATE DATABASE\|USE\|.*DROP DATABASE\).*`<old db name>`/d' | mysql <new db name>

pv is just there to show a progress bar. The line could have been written as

bunzip2 20171212.dump.bz2 | sed -e '/^\(CREATE DATABASE\|USE\|.*DROP DATABASE\).*`<old db name>`/d' | mysql <new db name>

sed removes the lines preventing the database name change without altering any text occurring into the dump file.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜