Creating a MySQL Database with Variables

I want to do something line by line

CREATE DATABASE IF NOT EXISTS @database_name;

From reading the mysql syntax for prepared statements, it seems like they cannot be used to create databases, otherwise something like this would be fine.

 SET @s = CONCAT('CREATE DATABASE IF NOT EXISTS ',@database_name); PREPARE stmt FROM @s; EXECUTE stmt; 

Ideally, I want it to somehow I can run from a .sql file from a shell script

 #!/bin/bash MYSQL="mysql" `${MYSQL} --version >& /dev/null` if [ $? != 0 ]; then MYSQL="mysql5" `${MYSQL} --version > /dev/null` if [ $? != 0 ]; then echo "Can't find mysql binary?" exit 1 fi fi ${MYSQL} -u root --password=###### -e "set @database_name:='ben_search';source CreateSkeleton.sql;" 

Any ideas?

+6
source share
1 answer

You can simply take the CREATE DATABASE statement away from your SQL file and release it from your shell script:

 #!/bin/bash dbname='my_db' mysql -e "CREATE DATABASE $dbname" mysql $dbname < /path/to/file/CreateSkeleton.sql 
+2
source

Source: https://habr.com/ru/post/897594/


All Articles