且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

从Bash脚本插入mysql

更新时间:2023-01-31 20:02:17

您可以在 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