我有以下代码(我知道如何以正确的方式进行这项工作,但将其作为示例仅用于提出问题并了解错误在哪里):
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 就不会退出程序。