MySQL 从bash脚本更新mysql db中的数据

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28462376/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 13:20:18  来源:igfitidea点击:

Updating data in mysql db from bash script

mysqlbashshellinsert

提问by Grant

It's my first time trying to insert some info in a mysql database with an executable .sh file.

这是我第一次尝试使用可执行的 .sh 文件在 mysql 数据库中插入一些信息。

I'm using the following bash script but it's not working. Obviously most of the vars below have been replaced and simplified for ease of understanding.

我正在使用以下 bash 脚本,但它不起作用。显然,为了便于理解,下面的大多数变量已被替换和简化。

#!/bin/bash

mysql -D mydbname -u mydbuser -p mydbpass <<EOF
INSERT INTO mytable (mycolumn) VALUES ('myvalue') WHERE id = '13';

exit;

You can see that I only want to insert my value in the row where id = 13 and this row does exist.

您可以看到我只想在 id = 13 且该行确实存在的行中插入我的值。

I don't think i'm formatting the query properly am I?

我认为我没有正确格式化查询,是吗?

EDIT : Ok after suggestions below i've now got this but it still doesn't work?

编辑:好的,在下面的建议之后,我现在得到了这个,但它仍然不起作用?

#!/bin/bash
mysql -D mydbname -u mydbuser -p mydbpass <<EOF
UPDATE mytable SET mycolumn = 'myvalue' WHERE id = '13';
exit;

回答by Grant

Found the answer after some trial and error.

经过一些试验和错误后找到了答案。

Just in case anybody else is looking to do the same thing it's :

以防万一其他人想做同样的事情:

#!/bin/bash

mysql -u username -puserpass dbname -e "UPDATE mytable SET mycolumn = 'myvalue' WHERE id='myid'";

Note that there is no space between the -p and your password -puserpassif you put a space there -p userpassit will prompt you for the password.

请注意, -p 和您的密码之间没有空格-puserpass如果您在那里放置空格-p userpass它将提示您输入密码。

Hope it helps somebody ;)

希望它可以帮助某人;)

回答by hari

The solution works like a charm as specified in the above post. You could also use the -D option while specifying the dbname.

该解决方案就像上面帖子中指定的魅力一样。您还可以在指定 dbname 时使用 -D 选项。

#!/bin/bash

mysql -u username -puserpass -D dbname -e "UPDATE mytable SET mycolumn = 'myvalue' WHERE id='myid'";

For additional reference on the options, refer below link: https://www.shellhacks.com/mysql-run-query-bash-script-linux-command-line/

有关选项的其他参考,请参阅以下链接:https: //www.shellhacks.com/mysql-run-query-bash-script-linux-command-line/

回答by Bouramas

Your query doesn't work as you have not typed EOF at the end of the script. See my example below.

您的查询不起作用,因为您没有在脚本末尾输入 EOF。请参阅下面的示例。

#!/bin/bash

mysql -u root -ppassword DB_NAME <<EOF
SELECT * FROM CUSTOMERS WHERE NAME='YOURNAME';
SELECT * FROM ANOTHER_TABLE WHERE SOMETHING_ELSE;
... more queries
EOF

Note that the -ppassword argument can be skipped if the connection does not require a password.

请注意,如果连接不需要密码,可以跳过 -ppassword 参数。