Jeff Storey
Jeff Storey

Reputation: 57212

mysql script no database selected

I'm trying to run some mysql scripts from the command line. One is autogenerated and it does not select the database before hand. Right now I have two scripts:

mysql -u <user> -p<password> < script1.sql
mysql -u <user> -p<password> < script2.sql

the last line of script1 is USE mydatabase; but when I run script2 it says there is no database selected. Is there a way to specify what database to use for script2?

Upvotes: 5

Views: 17090

Answers (4)

Matei Suica
Matei Suica

Reputation: 859

add the parameter -D like this

mysql -u<username> -p<password -D<database> < script.sql

Upvotes: 20

Jeremy J Starcher
Jeremy J Starcher

Reputation: 23873

Under *nix (Unix, Linux, etc) you can use the cat command to combine the two scripts.

cat script1.sql script2.sql | mysql -u <user> -p<password>

Under DOS/Windows you can a little known feature of the copy command

copy script1.sql+script2.sql | mysql -u <user> -p<password>

Upvotes: 0

Anshu
Anshu

Reputation: 7853

The solution by @Desislav would work (other solution is to add 'use database' command at top of script2.sql), but to clarify your issue

the last line of script1 is USE mydatabase; This would not help for script2, since script2 would be executed in a different process, you have to specify the database again.

Upvotes: 1

Desislav Kamenov
Desislav Kamenov

Reputation: 1203

mysql -u <user> -p<password> my_database_name < script2.sql

In your case happens because these are 2 separate processes and the queries from the first are not connected the ones from the second.

Another solution is to put USE database_name as first line in script2.sql

Upvotes: 5

Related Questions