简体   繁体   中英

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?

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.

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.

An empty list is returned when no more rows are available.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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