Search code examples
pythonmysqlcursortornado

tornado mysql: how to get size of cursor


Here is how tornado works with MySQL:

from __future__ import print_function
from tornado import ioloop, gen
import tornado_mysql


@gen.coroutine
def f():
    conn = yield tornado_mysql.connect(host='127.0.0.1', port=3306, user='user', passwd='passwd', db='mydb')
    cur = conn.cursor()
    yield cur.execute(query)   
    cur.close()
    conn.close()
    return cur

query = "select id from tablename"
for row in ioloop.IOLoop.current().run_sync(f):
    print(row)

If print(row) executes zero time, it means that select id from tablename got nothing.

I just want to know how to get the size of ioloop.IOLoop.current().run_sync(f) immediately (something like ioloop.IOLoop.current().run_sync(f).size == 0) so that I can determine whether some sql query got something or not.


Solution

  • It's not always possible to iterate over a python sequence more than once, or to know how many things are in a sequence without iterating over it. So to be safe, you must copy the result into a list:

    lst = list(IOLoop.current().run_sync(f))
    if lst:
        for row in lst:
            print(row)