简体   繁体   English

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

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

I have the following code (i know how to do this working and in the right style, but cited it as an example only to ask a question and understand where is mistake): 我有以下代码(我知道如何以正确的方式进行此工作,但仅将其作为示例提出问题并了解错误之处):

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

and second: 第二:

def gen():
    yield 'spam'

for i in gen():
    print i

# Process finished with exit code 0

I can't understand why the second example is one time and ends as it should, but the first performed one time and then freezes and does nothing. 我不明白为什么第二个示例是一次并按预期方式结束,但是第一个示例执行了一次,然后冻结并且什么也不做。 Why he doesn't stop with exit code 0? 为什么他不停止退出代码0?

Strange behavior : If to the second example add the following lines before cycle it prints 'spam' and "freezes" too: 奇怪的行为 :如果在第二个示例中,在循环之前添加以下行,则它也会打印“垃圾邮件”和“冻结”字样:

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)

Update Answer: Python does not come out of the program as long as it's time connection is closed. 更新答案:只要关闭连接,Python就不会退出程序。

i think what you should do in first case is 我认为你在第一种情况下应该做的是

result = cursor.fetchmany(5)

for item in result:
    yield item

fetchmany method fetches the next set of rows of a query results, returning a list of tuples. fetchmany方法获取查询结果的下一组行,并返回元组列表。

An empty list is returned when no more rows are available. 当没有更多行可用时,将返回一个empty list

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

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