15

I have a mysql dump with 5 databases and would like to know if there is a way to import just one of those (using mysqldump or other).

Suggestions appreciated.

1
  • I don't think there is. Importing all databases, and dropping every one except the one you want to keep, is the best thing you can do I think - but you never know, maybe somebody comes up with something
    – Pekka
    Aug 29, 2010 at 20:22

2 Answers 2

31

You can use the mysql command line --one-database option.

mysql> mysql -u root -p --one-database YOURDBNAME < YOURFILE.SQL

Of course be careful when you do this.

You can also use a mysql dumpsplitter.

6
  • I tried this, but always got the error "ERROR 1049 (42000): Unknown database 'redmine'". The documentation states: "This is useful for skipping updates to other databases in the binary log." This is not a binary log (I think) so it wont work. Aug 29, 2010 at 23:09
  • 1
    I found an interesting bug report relating to this feature: bugs.mysql.com/bug.php?id=40477 Aug 29, 2010 at 23:16
  • 1
    @ThePixelDeveloper: An empty database need to exist first, then it works. Sep 12, 2012 at 12:20
  • 2
    Ah, I finally understood what @RuneKaagaard meant: If you want to restore the "redmine" database, then first log in to mysql as root and do a "CREATE DATABASE redmine". Afterwards the "--one database" command switch will work afterwards.
    – stolsvik
    May 13, 2013 at 22:07
  • 2
    Oracle's documentation cautions against this command. It can easily end up with undexpected results. See dev.mysql.com/doc/refman/5.6/en/…
    – Nigel
    Oct 15, 2015 at 10:52
16

You can pipe the dumped SQL through sed and have it extract the database for you. Something like:

cat mysqldumped.sql | \
sed -n -e '/^CREATE DATABASE.*`the_database_you_want`/,/^CREATE DATABASE/ p' | \
sed -e '$d' | \
mysql

The two sed commands:

  1. Only print the lines matching between the CREATE DATABASE lines (including both CREATE DATABASE lines), and
  2. Delete the last CREATE DATABASE line from the output since we don't want mysqld to create a second database.

If your dump does not contain the CREATE DATABASE lines, you can also match against the USE lines.

1
  • In a single line, and with the -u and -p options: cat all-databases.sql | sed -n -e '/^CREATE DATABASE.*`the_database_you_want`/,/^CREATE DATABASE/ p' | sed -e '$d' | mysql -u my_username -p Dec 5, 2013 at 20:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.