Python MySQLdb:迭代游标 [英] Python MySQLdb: Iterating over a cursor

查看:231
本文介绍了Python MySQLdb:迭代游标的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在另一篇文章中,这段代码:

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',)

经过多次搜索,我一直无法理解这一点。有人可以解释这个区别吗?我无法弄清楚execute()返回的确切内容。另外,我无法弄清楚为什么第一个迭代器的形式 - 使用括号和逗号 - 工作。

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. Also, I cannot figure out why the form of the first iterator -- using parentheses and a comma -- works.

推荐答案

In本身, execute()不返回任何内容。一旦执行了查询,当你迭代游标时,你会从查询中获取数据作为元组。

In itself, execute() doesn't return anything. Once you've executed a query, you get the data back from the query as tuples when you iterate over the cursor.

你的查询只返回一列,所以你得到了1元组。

Your query returns only one column, so you get 1-tuples.

Python中的1元组看起来有点奇怪。 ()是一个空元组,而(1,2)是一个2元组,但(1)只是括号中的数字 1 ,而不是元组。因此,(1,)等1元组必须具有尾随逗号才能被识别为元组。

1-tuples in Python look a bit odd. () is an empty tuple, and (1, 2) is a 2-tuple, but (1) is just the digit 1 in parentheses, not a tuple. 1-tuples such as (1,) must therefore have the trailing comma in order to be recognised as tuples.

如果您运行了一个选择了三列的查询,您可以使用以下内容读取每行中的三个值:

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...

你的第一个代码也是这样做的,但它正在解包1元组而不是3元组。

Your first code is doing the same, but it's unpacking 1-tuples instead of 3-tuples.

另一方面,你的第二个代码只是迭代游标出来的内容,即1元组,而不进行任何解包。

On the other hand, your second code is simply iterating over what comes out of the cursor, i.e. the 1-tuples, without doing any unpacking.

这篇关于Python MySQLdb:迭代游标的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆