18

I am trying to create a batch file to create a MySQL Database. So far, none of the information I am finding is working. Just for testing, this is what I am trying...

C:\>mysql -uroot -ppassword < CREATE DATABASE testdb;
C:\>mysql -uroot -ppassword mysql < CREATE DATABASE testdb;

No matter how I put it, I keep getting the error "The system cannot find the file specified". If I just put...

C:\>mysql -uroot -ppassword

It logs into the MySQL prompt fine. What exactly am I doing wrong?

4 Answers 4

27

I agree with the other posters, it's much better to put the schema into a file. However, here's how you can do it on the command line:

mysql -uroot -ppassword -e "CREATE DATABASE testdb"
Sign up to request clarification or add additional context in comments.

Comments

8

acess as root user :

mysql -u root -p

it asks for password..enter your password

then run the create command like this:

mysql> create database database_name;

Comments

6

It's better to write your MySQL inside a file and then import that file. That way, when you need to run it again (reinstalling or migrating) you have a record of the MySQL to run. The code I use for a file like this is as follows, which destroys anything that's already there, and then creates the database and assigns a dedicated user.

# uninstall if anything's already there
GRANT ALL PRIVILEGES ON *.* TO 'username'@'%';
DROP USER 'username'@'%';
DROP DATABASE IF EXISTS `tablename`;

# create the user
CREATE USER 'username'@'%' IDENTIFIED BY 'password';
CREATE DATABASE IF NOT EXISTS `tablename`;
GRANT ALL PRIVILEGES ON `tablename` . * TO 'username'@'%';

1 Comment

That is perfect except I can't put it in a file. The batch script is written in our web panel, then executed on the relevant machine. This is the reason I am actually writing out the script rather than creating an .sql file and executing it. I was able to get the DB created with "mysqladmin -uroot -ppass CREATE testdb" but as far as creating users and assigning permissions, its not working too well.
5

Try putting your sql into a text file, like 'createDb.sql' and then run:

mysql -uroot -ppassword < createDb.sql; 

2 Comments

Are you sure it needs a semi-colon on the end?
@JW. no it doesn't. But it does no harm as shell eats it up.

Your Answer

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