Skip to content
Advertisement

sqlite cursor fetchone() returns ‘NoneType’?

I want to build a function that returns the lowest row count from all tables if the two scores scor1 and scor2 are not both 0 :

def mini(tablelist):
mini = 1000
for table in tablelist:
    c.execute("SELECT numar_par FROM " + table + "")
    c_min = len(c.fetchall())

    if c_min is None:
        mini = 0
    else:
        c.execute("SELECT scor1 FROM " + table + " ORDER BY numar_par DESC LIMIT 1")
        print("this is fetchone:",c.fetchone(),'from table: ',table)
        scor1 = c.fetchone()[0]
        c.execute("SELECT scor2 FROM " + table + " ORDER BY numar_par DESC LIMIT 1")
        scor2 = c.fetchone()[0]
        sum = int(scor1) + int(scor2)
        if c_min < mini and sum >0:
            mini = c_min
return mini

This is the result of the print statement:

this is fetchone: ('0',) from table:  a

and this is the error:

File "D:pariuripythonPycharm test1Test11 peste 0.5functii.py", line 181, in mini
scor1 = c.fetchone()[0]
TypeError: 'NoneType' object is not subscriptable

Advertisement

Answer

After executing a query with execute, the query results will be available in a query result set, which you can then iterate over with the c.fetch* methods.

The thing to note here, is that fetch* will iterate over the result set, exhausting it. This works similar to a generator, which you can only iterate over once.

It works something like this. Imagine a pointer pointing to the next row in the result set to be queried. Running c.execute gives a result set looking like this –

 head
   |____ Result 1
         Result 2
         .
         .
         Result N

After calling c.fetchone, head will return the next row, and advance by one row –

 head    Result 1 (returned)
   |____ Result 2
         .
         .
         Result N

Since you have only one row in your table, another call to fetchone returns an empty list.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement