MySQL 如何在执行 sql 脚本时回显打印语句
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8147834/
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
How to echo print statements while executing a sql script
提问by Joe
We have a simple sql script which needs to be executed against a MySQL database and we would like print log statements on the progress of the script (e.g. Inserted 10 records into foo or Deleted 5 records from bar). How do we do this?
我们有一个简单的 sql 脚本,它需要对 MySQL 数据库执行,我们想打印关于脚本进度的日志语句(例如,将 10 条记录插入 foo 或从 bar 中删除 5 条记录)。我们如何做到这一点?
- I would like to know the syntax to be used for insert/update/delete statements.
- How do I know about the number of rows affected by my statement(s).
- I would also like to control printing them using a ECHO off or on command at the top of the script.
- The script should be portable across Windows / Linux OS.
- 我想知道用于插入/更新/删除语句的语法。
- 我如何知道受我的语句影响的行数。
- 我还想使用脚本顶部的 ECHO off 或 on 命令来控制打印它们。
- 该脚本应该可以跨 Windows/Linux 操作系统移植。
回答by blankabout
This will give you are simple print within a sql script:
这将为您提供一个 sql 脚本中的简单打印:
select 'This is a comment' AS '';
Alternatively, this will add some dynamic data to your status update if used directly after an update
, delete
, or insert
command:
或者,这将一些动态数据添加到您的状态更新,如果后直接使用update
,delete
或insert
命令:
select concat ("Updated ", row_count(), " rows") as '';
回答by Craig Wayne
I don't know if this helps:
我不知道这是否有帮助:
suppose you want to run a sql script (test.sql) from the command line:
假设您想从命令行运行 sql 脚本 (test.sql):
mysql < test.sql
and the contents of test.sql is something like:
和 test.sql 的内容是这样的:
SELECT * FROM information_schema.SCHEMATA;
\! echo "I like to party...";
The console will show something like:
控制台将显示如下内容:
CATALOG_NAME SCHEMA_NAME DEFAULT_CHARACTER_SET_NAME
def information_schema utf8
def mysql utf8
def performance_schema utf8
def sys utf8
I like to party...
So you can execute terminal commands inside an sql statement by just using \!
, provided the script is run via a command line.
因此\!
,如果脚本是通过命令行运行的,您只需使用 即可在 sql 语句中执行终端命令。
\! #terminal_commands
回答by useless
Just to make your script more readable, maybe use this proc:
只是为了使您的脚本更具可读性,也许可以使用此过程:
DELIMITER ;;
DROP PROCEDURE IF EXISTS printf;
CREATE PROCEDURE printf(thetext TEXT)
BEGIN
select thetext as ``;
END;
;;
DELIMITER ;
Now you can just do:
现在你可以这样做:
call printf('Counting products that have missing short description');
回答by Mithun Sasidharan
You can use print -p -- in the script to do this example :
您可以在脚本中使用 print -p -- 来执行此示例:
#!/bin/ksh
mysql -u username -ppassword -D dbname -ss -n -q |&
print -p -- "select count(*) from some_table;"
read -p get_row_count1
print -p -- "select count(*) from some_other_table;"
read -p get_row_count2
print -p exit ;
#
echo $get_row_count1
echo $get_row_count2
#
exit