如何在批处理脚本的变量中存储sql查询的输出? [英] how to store output of sql query in variable in batch script?
问题描述
我正在处理批处理脚本.
i am working on a batch script.
我想将行的计数存储在变量中.
i want to store the count of row's in variable.
喜欢
set var = mysql -uroot -proot -e从表中选择count(*)";
set var = mysql -uroot -proot -e"select count(*) from table";
我也尝试过用其他方式做
i also tried to do it other way like
set var= mysql -uroot -proot -e "select count(*) from table into outfile 'F:\count.txt'";
for /f %%a in ("F:\count.txt") do (
set output = %%a
echo %output%
pause
)
在上面的代码中,变量输出"什么都没有显示(空).
In above code the variable "output" shows nothing(empty).
请帮帮我.
推荐答案
我可以在您的脚本中看到至少两个问题:
I can see at least two issues in your script:
-
在
IN( )
中用双引号引起来的字符串被视为文字,而不是文件路径/名称,除非您指定usebackq
选项,它强制执行不同的语义,从而将双引号字符串或未双引号的字符串都视为文件名.
A string in double quotes inside
IN( )
is treated as a literal, not as a file path/name, unless you specify theusebackq
option, which enforces different semantics, whereby either double-quoted string or non-quoted one is treated as a file name.
您要将<space>%%a
存储到output<space>
变量中,而不是将%%a
存储到output
中.
You are storing <space>%%a
into the output<space>
variable, not %%a
into output
.
在修复了这两个问题之后,将再有一个问题(可能只有一个).您正在为变量分配一个值,然后使用立即变量扩展(%var%
)在同一括号中的块(这是您的循环体)中评估该变量.这不能按预期方式工作.事实是,带括号的块被完全解析为一个单元,即在执行第一个命令之前先解析其所有命令.您可能会猜到,在这种情况下,您的%output%
表达式将没有任何结果,因为在解析时尚未为output
赋值. (并且为 分配了一个值时,它不会更改任何内容,因为先前的(空)值已经替换了该表达式.)
After you've fixed those two, there will remain one (probably, just one) more issue. You are assigning a value to a variable and then evaluating the variable in the same bracketed block (which is your loop body) using immediate variable expansion (%var%
). This cannot work as expected. The thing is, a bracketed block is parsed entirely as a single unit, i.e. all its commands are parsed before the first one executes. As you can guess, your %output%
expression will in this case evaluate to nothing, because output
is not yet assigned a value at the time of parsing. (And when it is assigned a value, it will change nothing, because the previous (empty) value will already have replaced the expression.)
您可以使用延迟变量扩展来解决此问题,可以猜测,延迟扩展使用了不同的评估时间.首先,您应该通过发出SETLOCAL EnableDelayedExpansion
命令来启用延迟扩展,然后使用稍微不同的语法:!var!
而不是%var%
.
You can solve this using delayed variable expansion, which, as can be guessed, uses a different timing for evaluation. First, you should enable delayed expansion by issuing the SETLOCAL EnableDelayedExpansion
command, then use a slightly different syntax: !var!
instead of %var%
.
因此,如果我们解决了上面提到的所有问题,则循环可能看起来像这样:
So, if we address all the issues mentioned above, the loop may look like this:
…
SETLOCAL EnableDelayedExpansion
FOR /F "usebackq" IN ("F:\count.txt") DO (
SET output=%%a
ECHO !output!
)
这篇关于如何在批处理脚本的变量中存储sql查询的输出?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!