简体   繁体   English

mysql如何通过bash脚本进行查询

[英]mysql how to make a query through bash script

How to make a mysql statement or query through bash script??如何通过bash脚本制作mysql语句或查询?? for example create a user and a database??例如创建一个用户和一个数据库?? i'm trying through a bash script to run a simple mysql statement我正在尝试通过 bash 脚本来运行一个简单的 mysql 语句


echo "insert database name"
read $db
echo "insert username "
read varname
echo "insert password for the user "
read -s varpass

sudo mysql -u root  -e <<EOF
CREATE DATABASE $db;
CREATE USER '$varname'@'localhost' IDENTIFIED BY '$varpass';
GRANT ALL ON $db.* TO '$varname'@'localhost' IDENTIFIED BY '$varpass' WITH GRANT OPTION;
FLUSH PRIVILEGES;
EXIT;
EOF

You can try this.你可以试试这个。

test.sh

#!/bin/bash

echo "insert database name"
read db
echo "insert username "
read varname
echo "insert password for the user "
read -s varpass

sudo mysql -u root mysql<<EOF
CREATE DATABASE $db;
CREATE USER '$varname'@'localhost' IDENTIFIED BY '$varpass';
GRANT ALL ON $db.* TO '$varname'@'localhost' WITH GRANT OPTION;
FLUSH PRIVILEGES;
\q
EOF

Note the changes:注意变化:

  • read $db was changed to read db - the $ was removed read $db更改为read db - $已删除
  • Database name was added before <<EOF<<EOF之前添加了数据库名称
  • Exit was replaced with \\q退出被替换为 \\q

What if your database had a password如果您的数据库有密码怎么办

You could create a file ~/.my.cnf with the following contents:您可以创建一个包含以下内容的文件~/.my.cnf

[client]
user=root
password=YourPassword123!!

Then, you can log on to mysql's mysql database using the command mysql mysql .然后,您可以使用命令mysql mysql登录到 mysql 的mysql数据库。 Using that, you can change just the <<EOF line to:使用它,您可以将<<EOF行更改为:

mysql mysql<<EOF

Everything else can remain the same.其他一切都可以保持不变。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM