5

I have a sql file that I want to upload from the command line. To do this I first need to go into MySQL and create the database

mysql> create database myDB;

and then call the following from the command line:

mysql -u username -p myDB < myDB.sql

Is there a way to do this all in one line from the command line?

I tried adding the following lines (and various combinations) to the beginning of the myDB.sql file:

create database `myDB`;
use `myDB`;

and then running

mysql -u username -p < myDB.sql

but that did not work.

ERROR 1046 (3D000) at line 7: No database selected

3 Answers 3

5

.sql files are generally LITERALLY just a sequence of SQL DDL/DML queries. If it was created by mysqldump, then it should contain EVERYTHING needed to recreate the database from the ground up, including the necessary create db and create table queries.

if they're not there, you can manually add them to the top of the file yourself via simple file concatenation/modification, e.g.

echo 'create database foo;' > new.sql
cat otherstuff.sql >> new.sql
mysql < new.sql
Sign up to request clarification or add additional context in comments.

8 Comments

Like I said in my question, I've tried that and it did not work. The top of the sql file LITERALLY says create database myDB; use myDB;
dose the account you're using to log into mysql have the permissions to do that? you'd definitely need to be granted the create permission.
well, I tried a basic create db/create table/insert thing, and if the db OR table already exists, then the rest of the script is ignored. check if the db already exists? or do create database if not exists instead, similarly for the tables.
so yeah. the create call (either of them) would fail if the table/db already existed, and that would abort the rest of the script. You may want to instead add a drop command first, especially if you're not 100% sure that the table structure WON'T change between dump/reload time. otherwise you may be inserting into a table whose structure is different. no biggie if you added fields, but if you removed/changed fields, you can end up with garbage in the db at best.
cat 'create database foo;' > new.sql returns cat: create database foo;: No such file or directory i believe it should be echo 'create database foo;' > new.sql
|
5

If you generated the mysqldump file with the --databases or --all-databases options, then it puts the correct CREATE DATABASE statements into the dump file.

Comments

0

MySQL reference article Copying MySQL Databases to Another Machine suggests a two-commands solution to this question, creating a database with the MySQL server administration program mysqladmin.

mysqladmin -u username -p create myDB
mysql -u username -p myDB < myDB.sql

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.