I have following method that access mysql database and the query get executed in a server that I don't have any access to change anything on regarding increasing memory. I am new to generators and started to read more about it and thought I could convert this to be use generator.
def getUNames(self):
globalUserQuery = ur'''SELECT gu_name FROM globaluser WHERE gu_locked = 0'''
global_user_list = []
try:
self.gdbCursor.execute(globalUserQuery)
rows = self.gdbCursor.fetchall()
for row in rows:
uName = unicode(row['gu_name'], 'utf-8')
global_user_list.append(uName)
return global_user_list
except Exception, e:
traceback.print_exc()
And I use this code as follow:
for user_name in getUNames():
...
This is the error that I was getting from server side:
^GOut of memory (Needed 725528 bytes)
Traceback (most recent call last):
...
packages/MySQLdb/connections.py", line 36, in defaulterrorhandler
raise errorclass, errorvalue
OperationalError: (2008, 'MySQL client ran out of memory')
How should I be using generator to avoid this:
while true:
self.gdbCursor.execute(globalUserQuery)
row = self.gdbCursor.fetchone()
if row is None: break
yield row
Not sure if the above is the right way to go since I am expecting a list as a result of my database method. I think what would be great is a get chunk from the query and return a list and once that get done generator would give the next set as long as query return results.