Home > Enterprise >  TypeError: 'NoneType' object is not subscriptable while using fetchone()
TypeError: 'NoneType' object is not subscriptable while using fetchone()

Time:11-04

cur.execute(""" 
            CREATE TEMPORARY VIEW bobby_view AS
            SELECT heading1, heading2
            FROM bobby 
            WHERE heading2 = %s; """, (variable,))


            cur.execute("""
            SELECT d1.heading1
            FROM bobby_view d1
            WHERE d1.heading1 >= ALL (
                SELECT d2.heading1
                FROM bobby_view d2);
            """) 
            
            answer = cur.fetchone()[0]

This produces the error:

TypeError: 'NoneType' object is not subscriptable

This is the structure of my code. Variable was an integer entered as a parameter to a function and it has been casted as a string prior to the above code.

The second block of code finds the heading1 data that is the highest. I've tested this on its own and I am fairly confident it works. Because of this, I think the error comes from variable not being used in the view properly. Any help or advice would be greatly appreciated.

CodePudding user response:

Try:

cur.execute("""
        SELECT d1.heading1
        FROM bobby_view d1
        WHERE d1.heading1 >= ALL (
            SELECT d2.heading1
            FROM bobby_view d2);
        """) 
        
        answer = cur.fetchone()
        answer = answer[0] of answer else 'default'

CodePudding user response:

you can refer the documentation here

fetchone returns the next row of a query result set and returns a single sequence, or None if no more rows are available, so if you are fetching the last row the error will occur. Try something like this,

answer = cur.fetchone()
while answer is not None:
  print(answer)
  answer = cur.fetchone()
  • Related