从Bash脚本插入mysql [英] Insert into mysql from Bash script
问题描述
在这里利用了一些帖子以及Google和朋友,我在拼命地尝试使工作变得简单.我想通过bash脚本将数据插入mysql.
Utilized a few posts here and Google and friends and I'm trying desperately to get something simple to work. I want to insert data into mysql via a bash script.
#!/bin/bash -x
DB_USER='jhatter';
DB_PASSWD='XXXXXXX';
DB_NAME='ppr';
TABLE='graph';
#Collect Rank Information from flightaware.com
day=$(date +"%m/%d/%y")
time=$(date +"%H:%M:%S")
rank=$(curl -s http://flightaware.com/adsb/stats/user/jdhatter11 | grep -i site-ranking-29371 | grep window | awk '{print $2}' | sed s/,//)
#mysql commands
mysql --user=$DB_USER --password=$DB_PASSWD $DB_NAME
INSERT INTO $TABLE (`id `, `day`, `time`, `rank`) VALUES (NULL, "$day", "$time", "$rank");
QUIT;
此脚本在mysql登录后手动停止运行.它实际上使登录显示在屏幕上,并且我已插入数据库中. 我是个新手,如果很公然,请放轻松,但是为什么脚本不继续处理INSERT却把我扔到mysql中. 我预想这一切都是在后台发生的...
This script when ran manually stops abrubtly after mysql login. It actually brings the login up on screen and I have been inserted in the database. I'm a huge novice and please go easy if it's blatant, but why doesn't the script proceed to process the INSERT and instead throw me into mysql. I envision this all happening in the background...
推荐答案
您可以在 here-document 中传递命令,如下所示:
You can pass the commands in a here-document, like this:
mysql --user=$DB_USER --password=$DB_PASSWD $DB_NAME << EOF
INSERT INTO $TABLE (\`id\`, \`day\`, \`time\`, \`rank\`) VALUES (NULL, "$day", "$time", "$rank");
EOF
注意`
需要转义.
我还删除了QUIT
命令,
因为这是不必要的(很好的提示@Ven,谢谢).
Notice that the `
need to be escaped.
I also removed the QUIT
command,
as it's unnecessary (good tip @Ven, thanks).
实际上,由于这些列名称不包含特殊符号, 您实际上并不需要引用它们,而编写INSERT查询则更为简单,如下所示:
Actually, since those column names don't contain special symbols, you don't actually need to quote them, and write the INSERT query a bit simpler, like this:
mysql --user=$DB_USER --password=$DB_PASSWD $DB_NAME << EOF
INSERT INTO $TABLE (id, day, time, rank) VALUES (NULL, "$day", "$time", "$rank");
EOF
这篇关于从Bash脚本插入mysql的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!