Reputation: 1790
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.
Upvotes: 0
Views: 2926
Reputation: 14864
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.
Upvotes: 1