繁体   English   中英

为什么python语句yield用游标表现为这种方式?

[英]Why does python statement yield behave this way with cursor?

我有以下代码(我知道如何以正确的方式进行此工作,但仅将其作为示例提出问题并了解错误之处):

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就不会退出程序。

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

result = cursor.fetchmany(5)

for item in result:
    yield item

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

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

暂无
暂无

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

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