1.7.2.4 '--' as the Start of a Comment作为注释的开始

Standard SQL uses the C syntax /* this is a comment */ for comments, and MySQL Server supports this syntax as well. 标准SQL使用C语法/* this is a comment */,MySQL Server也支持此语法。MySQL also support extensions to this syntax that enable MySQL-specific SQL to be embedded in the comment, as described in Section 9.7, “Comments”.MySQL还支持对该语法的扩展,使MySQL特定的SQL能够嵌入注释中,如第9.7节,“注释”所述。

Standard SQL uses -- as a start-comment sequence. MySQL Server uses # as the start comment character. 标准SQL使用“--”作为开始注释序列。MySQL Server使用#作为开始注释字符。MySQL Server also supports a variant of the -- comment style. MySQL Server还支持--注册样式的变体。That is, the -- start-comment sequence must be followed by a space (or by a control character such as a newline). 也就是说,--开头的注释序列后面必须跟一个空格(或一个控制字符,如换行符)。The space is required to prevent problems with automatically generated SQL queries that use constructs such as the following, where we automatically insert the value of the payment for payment:需要该空间来防止自动生成的SQL查询出现问题,这些查询使用以下结构,其中我们自动插入payment的值:

UPDATE account SET credit=credit-payment

Consider about what happens if payment has a negative value such as -1:考虑一下如果payment为负值(如-1)会发生什么:

UPDATE account SET credit=credit--1

credit--1 is a valid expression in SQL, but -- is interpreted as the start of a comment, part of the expression is discarded. 在SQL中是一个有效的表达式,但是--被解释为注释的开头时,该表达式的一部分将被丢弃。The result is a statement that has a completely different meaning than intended:结果是一个与预期意义完全不同的陈述:

UPDATE account SET credit=credit

The statement produces no change in value at all. This illustrates that permitting comments to start with -- can have serious consequences.该语句的值根本不会发生变化。这说明允许评论一开始就可能产生严重后果。

Using our implementation requires a space following the -- for it to be recognized as a start-comment sequence in MySQL Server. 使用实现需要在--后面有一个空格,以便在MySQL Server中将其识别为开始注释序列。Therefore, credit--1 is safe to use.因此,credit--1可以安全使用。

Another safe feature is that the mysql command-line client ignores lines that start with --.另一个安全的特性是mysql命令行客户端忽略以--开头的行。