Search code examples
pythonmysqlerror-handlingtypeerrornonetype

Im getting the "nonetype" error but i cant figure out why


so i basically know what the Error means but i don't know why i'm getting it.I want to insert my cvs file into a table. Some of the rows are empty, thats why im using the if None...

The Error im getting:

File "C:\Users\Desktop\IngestData.py", line 64, in institutions cokey = temp[0] TypeError: 'NoneType' object is not subscriptable

Hope somebody can help me! Thank you in advance!

def institutions(cur):
    with open('persons.csv', 'r', encoding="utf-8") as g:
        #tempo = None
        reader = csv.reader(g)
        next(reader)
        for row in reader:
            if row[4] is None:
                break
            else:
                cur.execute("SELECT COKEY FROM countries WHERE Name = (%s)", [row[4]])
                temp = cur.fetchone()
                cokey = temp[0]
                cur.execute("""INSERT INTO institutions (Name,cokey) VALUES (%s,%s)
                            ON CONFLICT DO NOTHING;""",[row[3],cokey])

Solution

  • Does your database have any matching rows? cur.fetchone() is returning None, that's why your error is saying that NoneType is not suscriptable.

    def institutions(cur):
        with open('persons.csv', 'r', encoding="utf-8") as g:
            #tempo = None
            reader = csv.reader(g)
            next(reader)
            for row in reader:
                if row[4] is None:
                    break
                else:
                    cur.execute("SELECT COKEY FROM countries WHERE Name = (%s)", [row[4]])
                    temp = cur.fetchone()
                    if temp:
                        cokey = temp[0]
                        cur.execute("""INSERT INTO institutions (Name,cokey) VALUES (%s,%s) ON CONFLICT DO NOTHING;""",[row[3],cokey])