3.5 Using mysql in Batch Mode在批处理模式下使用mysql

In the previous sections, you used mysql interactively to enter statements and view the results. 在前面的部分中,您以交互方式使用mysql输入语句并查看结果。You can also run mysql in batch mode. 您还可以在批处理模式下运行mysqlTo do this, put the statements you want to run in a file, then tell mysql to read its input from the file:为此,请将要运行的语句放在一个文件中,然后告诉mysql从该文件读取其输入:

shell> mysql < batch-file

If you are running mysql under Windows and have some special characters in the file that cause problems, you can do this:如果您在Windows下运行mysql,并且文件中有一些导致问题的特殊字符,则可以执行以下操作:

C:\> mysql -e "source batch-file"

If you need to specify connection parameters on the command line, the command might look like this:如果需要在命令行上指定连接参数,该命令可能如下所示:

shell> mysql -h host -u user -p < batch-file
Enter password: ********

When you use mysql this way, you are creating a script file, then executing the script.当您以这种方式使用mysql时,您正在创建一个脚本文件,然后执行该脚本。

If you want the script to continue even if some of the statements in it produce errors, you should use the --force command-line option.如果希望脚本继续运行,即使其中的某些语句产生错误,则应使用--force命令行选项。

Why use a script? Here are a few reasons:为什么要使用脚本?以下是一些原因:

The default output format is different (more concise) when you run mysql in batch mode than when you use it interactively. 在批处理模式下运行mysql时,默认输出格式与以交互方式使用mysql时不同(更简洁)。For example, the output of SELECT DISTINCT species FROM pet looks like this when mysql is run interactively:例如,当以交互方式运行mysql时,SELECT DISTINCT species FROM pet的输出如下所示:

+---------+
| species |
+---------+
| bird    |
| cat     |
| dog     |
| hamster |
| snake   |
+---------+

In batch mode, the output looks like this instead:在批处理模式下,输出如下所示:

species
bird
cat
dog
hamster
snake

If you want to get the interactive output format in batch mode, use mysql -t. 如果您想在批处理模式下获得交互式输出格式,请使用mysql-tTo echo to the output the statements that are executed, use mysql -v.要将执行的语句回显到输出,请使用mysql -v

You can also use scripts from the mysql prompt by using the source command or \. command:您还可以使用source命令或\.命令,从mysql提示符使用脚本:

mysql> source filename;
mysql> \. filename

See Section 4.5.1.5, “Executing SQL Statements from a Text File”, for more information.有关更多信息,请参阅第4.5.1.5节,“从文本文件执行SQL语句”