从python游标执行sql查询时,为什么需要使用3个引号?
我遇到了一些连接到MySQL数据库的Python程序.在代码中,我看到execute()
函数中的查询用3个引号("""
)括起来.我想知道原因.我还注意到,仅在创建,插入和更新表时才使用3个引号,而在选择行时则不使用.
I came across some Python programs that connect to a MySQL database. In the code, I saw the query in the execute()
function is enclosed withing 3 quotations("""
). I would like to know the reason for this. I also noticed that 3 quotes are used only while creating, inserting, and updating the table and not while selecting a row.
cursor.execute("""create table student(id char(10),name char(10))""")
cursor.execute("select * from student")
为什么?
不需要-出于某种原因而决定使用它的编码人员(可能是对该部分有所侧重).
It is not needed--the coder who made that just decided to use it for some reason (probably to add emphasis on that part).
用三引号引起来的字符串就是:一个字符串.它具有与常规字符串对象相同的属性.仅有两个区别:
A triple-quoted string is just that: a string. It has the same properties as a regular string object. There are only two differences:
- 它支持多行.这样可以避免每次需要换行时都必须放置
\n
的情况. - 它允许您使用单引号和双引号而不进行转义.这对于SQL命令可能很有用.
- It supports multiple lines. This saves you from having to place
\n
every time you want a newline. - It allows you to have single and double quotes without escaping. This could be useful with SQL commands.
总而言之,三引号字符串是一个字符串:
In summary though, a triple-quoted string is a string:
>>> type("""a""")
<type 'str'>
>>> type("a")
<type 'str'>
>>>
,并且该代码中不需要.