João Santos
João Santos

Reputation: 33

"TypeError: 'NoneType' object is unsubscriptable" while using fetchone()[0]

I'm having an issue with fetchone() function on the sqlite3 lib object connect:

Executed code:

conn = sqlite3.connect(sqlite_file)
c = conn.cursor()
c.execute("SELECT average from logs WHERE process = (?)", (process,))
print c.fetchone()
print "\n"
if c.fetchone() is not None:
    lastaverage = c.fetchone()[0]
    print lastaverage
    print average
    if average > lastaverage * 1.3:
        print "The process took too long to execute."
    else:
        lastaverage = 0
        print "Script entered here!!"

And here's my output:

Script entered here!!

(u'0',)


Script entered here!!

(u'200',)


Script entered here!!

None


Script entered here!!

(u'0',)

Traceback (most recent call last):
  File "script.py", line 87, in <module>
    lastaverage = c.fetchone()[0]
TypeError: 'NoneType' object is unsubscriptable

From what I searched, this is the same exact error that happens if I try to do lastaverage = None[0] which makes sense. But this line is only executed IF c.fetchone() returns a value.

Using if c.fetchone()[0] is not None: returns the same error, but on the if line! This seems like a clue but I don't know to what exactly. I also tried using if c.fetchone()[0]: instead of the is not None condition, but the behavior is the same.

My python version is 2.6.6. Any help will be appreciated.

Upvotes: 2

Views: 879

Answers (1)

holdenweb
holdenweb

Reputation: 37113

I believe the mistake you are making is that second call to fetchone(), which almost by definition can only be called once on a cursor that has executed a query returning a single row. Try saving the result and using the saved value rather than calling fetchone() twice without executing a second query. The first call exhausts the result set, so the second one returns None.

fetchone returns a single row, so fetchone()[0] gives you the first (and in this case the only) column from that row. but only when fetchone is actually returning a row!

Upvotes: 3

Related Questions