NoneType object returned by .fetchone() in MySQLdb

Peter Otten __peter__ at web.de
Wed Nov 26 16:17:08 EST 2003


Arnaud-F. FAUSSE wrote:

> I wrote code to store and fetch information from MySQL, and I have this
> problem:
> - using .fetchall(), I get tuples (correct according to specification)
> - using .fetchone(), I get NoneType object, that I have many problems to
> use
> :-(
> Did I miss somthing ?
> 
> Any clue ?

Are you testing with code like below?

cs = conn.cursor()
cs.execute("select * from mytable;")
cs.fetchall()
cs.fetchone()

fetchall() moves the cursor after the last row. When you invoke fetchall()
again it will return an empty list whereas fetchone() will return None.
To fix it, just execute the cursor before fetchone(), e. g:

cs.execute("select * from mytable;")
while 1:
    row = cs.fetchone()
    if row is None: break
    # process row

#this might also work (it does for sqlite)
cs.execute("select * from mytable;")
for row in cs:
    # process row
        
Of course I'm just guessing. It could also be an sql select that returns no
rows or something entirely different. Please post a minimal example code
next time you have a problem.

Peter




More information about the Python-list mailing list