简体   繁体   English

如何为MySQL制作Bash插入脚本

[英]How to make a Bash insert script for MySQL

I've been trying for two days to make a simple script which feeds an argument (a query) to mysql -e for it to execute. 我已经尝试了两天,以制作一个简单的脚本,该脚本将参数(查询)提供给mysql -e以使其执行。 But I can't use mysql -e inside the script for some reason, here are my testings : 但是由于某种原因,我不能在脚本内使用mysql -e ,这是我的测试:

I can run the following line in my bash with success : 我可以成功地在bash中运行以下行:

mysql -u abrouze -p simubase -e "insert into Processing values(1,2,3,'coca cola')"

It might be important to note that I need to pass full strings with whitespaces in the values. 需要特别注意的是,我需要在值中传递带有空格的完整字符串。

Now, here is my script : 现在,这是我的脚本:

#!/bin/bash
req="\"$1\""
echo $req
mysql -u abrouze -p simubase -e $req

Escaping quotes here so $req is really surrounded by quotes, and it doesn't work. 在这里将引号转义,因此$ req实际上被引号包围,并且不起作用。

Trace : 跟踪:

brouze@lasb-ida:~$ ./myrage.sh "insert into Processing values(1,2,3,'huge bear')"
"insert into Processing values(1,2,3,'huge bear')"

mysql  Ver 14.14 Distrib 5.5.35, for debian-linux-gnu (x86_64) using readline 6.2
Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved.

Following this, the help wall-of-text. 在此之后,帮助文本墙。

It seems absolutely trivial to me, I absolutely don't know how it would not work... 在我看来,这绝对是微不足道的,我绝对不知道它怎么行不通...

You can use a heredoc for this, have your script be: 您可以为此使用heredoc ,脚本如下:

#!/bin/bash
mysql -u abrouze -p simubase << EOF
$1
EOF

Then call your script as before: 然后像以前一样调用您的脚本:

./myrage.sh "insert into Processing values(1,2,3,'huge bear');"

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

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