0

我有以下代码(我知道如何以正确的方式进行这项工作,但将其作为示例仅用于提出问题并了解错误在哪里):

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

4

1 回答 1

1

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

result = cursor.fetchmany(5)

for item in result:
    yield item

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

empty list当没有更多行可用时返回An 。

于 2013-02-24T09:47:54.220 回答