我有一个 q.sql
文件,其中包含如下查询
SET SQL_SAFE_UPDATES = 0;
UPDATE student SET gender = 'f' WHERE gender = 'm';
.
.
UPDATE student SET rollno = '03' WHERE rollno = '003';
这个 .sql 文件是通过 shellscript 执行的:
mysql -uuser -ppass DB < q.sql
即使 q.sql
文件中的查询之一失败,该命令也会执行。现在我想验证所有查询是否都已成功更新。
我尝试echo $?
,但它总是打印 0,即命令成功,即使 q.sql
中的查询之一失败。
mysql -uuser -ppass DB < q.sql
echo $?
如果查询失败,我希望它打印“失败”或停止 shellscript 的进一步执行。
最佳答案
如果您使用bash
,则可以在脚本中使用set -e
并使用-e
执行mysql脚本的每一行选项。
#!/bin/bash
set -e
while read line; do
mysql -uuser -ppass DB -e "$line"
done < q.sql
有关信息set --help
显示:
-e Exit immediately if a command exits with a non-zero status.
和man mysql
页面:
--execute=statement, -e statement
Execute the statement and quit. The default output format is like that produced with --batch. See Section 4.2.3.1, "Using Options on the Command Line", for some examples. With this option, mysql does not use the history file.
关于mysql - 如何通过shell脚本验证test.sql文件中的所有查询是否都成功执行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57621255/