开发者

Creating MySQL database with variables

I want to do something along the lines of

CREATE DATABASE IF NOT EXISTS @database_name;

From reading the mysql syntax for prepared statements it appears that they cant be used to create databases, otherwise something like this would have been ok.

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

Ideally I want it as something 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?


You could just take the CREATE DATABASE statement away from your SQL file and issue it from your shell script:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜