简体   繁体   English

Python MySQLdb:在游标上迭代

[英]Python MySQLdb: Iterating over a cursor

In another post, this code: 在另一篇文章中,此代码:

connection = MySQLdb.connect(...)
cursor = connection.cursor()
cursor.execute("SHOW TABLES")
for (table_name,) in cursor:
    print(table_name)

correctly iterates over the table names in the cursor whereas this code: 正确地迭代游标中的表名,而此代码是:

for table_name in cursor:
    print(table_name)

returns elements in the form: 返回以下形式的元素:

('some_table',)

After much searching, I have been unable to make sense of this. 经过大量搜索,我无法理解这一点。 Could someone explain the difference? 有人可以解释其中的区别吗? I cannot figure out exactly what execute() is returning. 我不能弄清楚究竟execute()返回什么。 Also, I cannot figure out why the form of the first iterator -- using parentheses and a comma -- works. 另外,我无法弄清楚为什么第一个迭代器的形式(使用括号和逗号)会起作用。

In itself, execute() doesn't return anything. 本身, execute()不返回任何内容。 Once you've executed a query, you get the data back from the query as tuples when you iterate over the cursor. 执行查询后,在游标上进行迭代时,您会以元组的形式从查询中返回数据。

Your query returns only one column, so you get 1-tuples. 您的查询仅返回一列,因此得到1个元组。

1-tuples in Python look a bit odd. Python中的1元组看起来有些奇怪。 () is an empty tuple, and (1, 2) is a 2-tuple, but (1) is just the digit 1 in parentheses, not a tuple. ()是一个空元组,而(1, 2)是一个2元组,但是(1)只是括号中的数字1 ,而不是一个元组。 1-tuples such as (1,) must therefore have the trailing comma in order to be recognised as tuples. 因此(1,)诸如(1,)类的1元组必须具有尾随逗号才能被识别为元组。

If you ran a query that selected three columns, you could read the three values out from each row using something like the following: 如果运行的查询选择了三列,则可以使用以下内容从每一行中读取三个值:

cursor.execute("SELECT a, b, c FROM some_table")
for (a_value, b_value, c_value) in cursor:
    # do stuff...

Your first code is doing the same, but it's unpacking 1-tuples instead of 3-tuples. 您的第一个代码执行的操作相同,但是将1个元组而不是3个元组解包。

On the other hand, your second code is simply iterating over what comes out of the cursor, ie the 1-tuples, without doing any unpacking. 另一方面,您的第二个代码只是简单地遍历从游标出来的内容(即1元组),而无需进行任何拆包。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM