这篇文章介绍一下如何对mysql执行的sql语句结果进行判断。
环境准备
环境准备可参看:
注:已有MySQL的可以跳过此步骤。
常见问题
在mysql中执行sql语句,如果直接使用命令行的方式调用时会碰到两个问题:
- 问题1: 需要进行交互性的输入
- 问题2:多行输出的时候,如果使用了force选项,命令的结果是最后一条执行的状态,如果中间出错,无法确认此种情况。
解决方式
在脚本调用里,解决方式如下
- 问题1可以通过前文提到的Here Document或者-e选项来解决。
- 问题2,则可以通过对输出的判断来进行,不过MySQL中的错误不像Oracle基本可以通过ORA-的关键字确认出绝大部分,不过一般ERROR关键字是可以使用的,但是需要防止结果中出现ERROR而产生的误报。
方式1: 通过执行结果判断是否出错
- 使用force选项的多行语句,即使中间有错误,结果也不会返回失败,执行示例如下所示:
liumiaocn:~ liumiao$ mysql -uroot -proot --force <<EOF
> select version();
> errorcommand;
> select "Hello LiuMiao" as "Greetings";
> EOF
mysql: [Warning] Using a password on the command line interface can be insecure.
version()
8.0.11
ERROR 1064 (42000) at line 2: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'errorcommand' at line 1
Greetings
Hello LiuMiao
liumiaocn:~ liumiao$ echo $?
0
liumiaocn:~ liumiao$
- 不使用force选项的多行语句,缺省状态下碰到失败就会停止,结果可以用来判断,可适用于单行命令和缺省状态下的命令执行结果的判断,执行示例如下所示:
mysql -uroot -proot <<EOF
select version();
errorcommand;
select "Hello LiuMiao" as "Greetings";
EOF
- 1
- 2
- 3
- 4
- 5
从如下执行结果中可以看到,通过结果是能够判断是否执行出错的。
liumiaocn:~ liumiao$ mysql -uroot -proot <<EOF
> select version();
> errorcommand;
> select "Hello LiuMiao" as "Greetings";
> EOF
mysql: [Warning] Using a password on the command line interface can be insecure.
version()
8.0.11
ERROR 1064 (42000) at line 2: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'errorcommand' at line 1
liumiaocn:~ liumiao$ echo $?
1
liumiaocn:~ liumiao$
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
方式2: 通过输出判断是否出错
输出分为标准输出和标准错误两种,输入输出的FD分别为:
- 标准输入:0
- 标准输出:1
- 标准错误:2
通过结果输出的信息进行辅助判断,为了保证标准错误的信息不被遗漏,需要将标准错误和重定向到标准输出中,在bshell中写法如下:
>输出文件名称 2>&1
结合本文的例子,使用方式如下:
mysql -uroot -proot --force <<EOF >output.info 2>&1
select version();
errorcommand;
select "Hello LiuMiao" as "Greetings";
EOF
- 1
- 2
- 3
- 4
- 5
将结果全部输出到文件之中,然后通过错误关键字进行确认,执行如下所示
liumiaocn:~ liumiao$ mysql -uroot -proot --force <<EOF >output.info 2>&1
> select version();
> errorcommand;
> select "Hello LiuMiao" as "Greetings";
> EOF
liumiaocn:~ liumiao$ grep -w ERROR output.info
ERROR 1064 (42000) at line 2: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'errorcommand' at line 1
liumiaocn:~ liumiao$
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
注意:使用这种方式仍然需要确认是否会出现误报和漏报的情况。