为什么python语句yield会以这种方式使用游标?

时间:2013-02-24 09:41:26

标签: python cursor mysql-python yield

我有以下代码(我知道如何以正确的方式进行此工作,但仅作为示例引用问题并了解错误的位置):

import MySQLdb
import MySQLdb.cursors
connection = MySQLdb.connect(
        host=host, port=port, user=username, passwd=password, db=database, 
        cursorclass=MySQLdb.cursors.SSCursor)
cursor = connection.cursor()
sql = 'SELECT * FROM EXAMPLE_TABLE'
cursor.execute(sql)

def gen():
    yield cursor.fetchmany(5)

for i in gen():
    print i

和第二:

def gen():
    yield 'spam'

for i in gen():
    print i

# Process finished with exit code 0

我无法理解为什么第二个例子是一次并且应该结束,但是第一个例子执行了一次然后冻结并且什么都不做。为什么他没有停止退出代码0?

奇怪的行为: 如果在第二个示例中,在循环之前添加以下行,则会打印“垃圾邮件”并“冻结”:

connection = MySQLdb.connect(
        host=host, port=port, user=username, passwd=password, db=database, 
        cursorclass=MySQLdb.cursors.SSCursor)
cursor = connection.cursor()
sql = 'SELECT * FROM EXAMPLE_TABLE'
cursor.execute(sql)

更新 答:只要关闭时间连接,Python就不会出现在程序中。

1 个答案:

答案 0 :(得分:1)

我认为你应该在第一种情况下做的是

result = cursor.fetchmany(5)

for item in result:
    yield item

fetchmany方法获取查询结果的下一组行,返回元组列表。

当没有更多行可用时,将返回empty list

相关问题