mysql - How to create a database from shell command?

ID : 20331

viewed : 17

Tags : mysqlshellcommand-linemysql

Top 5 Answer for mysql - How to create a database from shell command?

vote vote

97

You mean while the mysql environment?

create database testdb; 

Or directly from command line:

mysql -u root -e "create database testdb";  
vote vote

82

cat filename.sql | mysql -u username -p # type mysql password when asked for it 

Where filename.sql holds all the sql to create your database. Or...

echo "create database `database-name`" | mysql -u username -p 

If you really only want to create a database.

vote vote

70

If you create a new database it's good to create user with permissions only for this database (if anything goes wrong you won't compromise root user login and password). So everything together will look like this:

mysql -u base_user -pbase_user_pass -e "create database new_db; GRANT ALL PRIVILEGES ON new_db.* TO new_db_user@localhost IDENTIFIED BY 'new_db_user_pass'" 

Where:
base_user is the name for user with all privileges (probably the root)
base_user_pass it's the password for base_user (lack of space between -p and base_user_pass is important)
new_db is name for newly created database
new_db_user is name for the new user with access only for new_db
new_db_user_pass it's the password for new_db_user

vote vote

60

mysqladmin -u$USER -p$PASSWORD create $DB_NAME 

Replace above variables and you are good to go with this oneliner. $USER is the username, $PASSWORD is the password and $DB_NAME is the name of the database.

vote vote

51

Use

$ mysqladmin -u <db_user_name> -p create <db_name> 

You will be prompted for password. Also make sure the mysql user you use has privileges to create database.

Top 3 video Explaining mysql - How to create a database from shell command?

Related QUESTION?