4.5.1.5 Executing SQL Statements from a Text File从文本文件执行SQL语句

The mysql client typically is used interactively, like this:mysql客户端通常以交互方式使用,如下所示:

mysql db_name

However, it is also possible to put your SQL statements in a file and then tell mysql to read its input from that file. 但是,也可以将SQL语句放在一个文件中,然后告诉mysql从该文件中读取其输入。To do so, create a text file text_file that contains the statements you wish to execute. 为此,请创建一个文本文件text_file,其中包含要执行的语句。Then invoke mysql as shown here:然后调用mysql,如下所示:

mysql db_name < text_file

If you place a USE db_name statement as the first statement in the file, it is unnecessary to specify the database name on the command line:如果将USE db_name语句作为文件中的第一条语句,则不必在命令行上指定数据库名称:

mysql < text_file

If you are already running mysql, you can execute an SQL script file using the source command or \. command:如果您已经在运行mysql,则可以使用source命令或\.命令执行SQL脚本文件:

mysql> source file_name
mysql> \. file_name

Sometimes you may want your script to display progress information to the user. For this you can insert statements like this:有时,您可能希望脚本向用户显示进度信息。为此,您可以插入如下语句:

SELECT '<info_to_display>' AS ' ';

The statement shown outputs <info_to_display>.显示的语句输出<info_to_display>

You can also invoke mysql with the --verbose option, which causes each statement to be displayed before the result that it produces.您还可以使用--verbose选项调用mysql,这会导致每条语句都显示在它产生的结果之前。

mysql ignores Unicode byte order mark (BOM) characters at the beginning of input files. mysql忽略输入文件开头的Unicode字节顺序标记(BOM)字符。Previously, it read them and sent them to the server, resulting in a syntax error. 以前,它会读取它们并将其发送到服务器,从而导致语法错误。Presence of a BOM does not cause mysql to change its default character set. BOM的存在不会导致mysql更改其默认字符集。To do that, invoke mysql with an option such as --default-character-set=utf8.为此,使用诸如--default-character-set=utf8之类的选项调用mysql。

For more information about batch mode, see Section 3.5, “Using mysql in Batch Mode”.有关批处理模式的更多信息,请参阅第3.5节,“在批处理模式下使用mysql”