How to create a database from shell command?

前端 未结 8 1718
难免孤独
难免孤独 2021-01-29 17:24

I\'m looking for something like createdb in PostgreSQL or any other solution that would allow me to create database with a help of a shell command. Any hints?

相关标签:
8条回答
  • 2021-01-29 18:03
    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.

    0 讨论(0)
  • 2021-01-29 18:04

    You can use SQL on the command line:

    echo 'CREATE DATABASE dbname;' | mysql <...>
    

    Or you can use mysqladmin:

    mysqladmin create dbname
    
    0 讨论(0)
  • 2021-01-29 18:06

    You mean while the mysql environment?

    create database testdb;
    

    Or directly from command line:

    mysql -u root -e "create database testdb"; 
    
    0 讨论(0)
  • 2021-01-29 18:06

    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.

    0 讨论(0)
  • 2021-01-29 18:06

    The ist and 2nd answer are good but if anybody is looking for having a script or If you want dynamic i.e (db/username/password in variable) then here:

    #!/bin/bash
    
    
    
    DB="mydb"
    USER="user1"
    PASS="pass_bla"
    
    mysql -uroot -prootpassword -e "CREATE DATABASE $DB CHARACTER SET utf8 COLLATE utf8_general_ci";
    mysql -uroot -prootpassword -e "CREATE USER $USER@'127.0.0.1' IDENTIFIED BY '$PASS'";
    mysql -uroot -prootpassword -e "GRANT SELECT, INSERT, UPDATE ON $DB.* TO '$USER'@'127.0.0.1'";
    
    0 讨论(0)
  • 2021-01-29 18:06

    Connect to DB using base user: mysql -u base_user -pbase_user_pass And execute CREATE DATABASE, CREATE USER and GRANT PRIVILEGES Statements.

    Here's handy web wizard to help you with statements www.bugaco.com/helpers/create_database.html

    0 讨论(0)
提交回复
热议问题