0

I have written some SQL data, but when I want to do a fetchone()[0] method to extract the first value of the row, but it returns a traceback stating that "'nontype' object is not subscriptable". I just don't know how to fix that.

I have deleted the [0] part and the traceback disappears, but I need to extract the first value, so the [0] is kind of essential part.

cur.execute('''INSERT OR IGNORE INTO Artist(name) VALUES(?)''',(artist,))
cur.execute('''SELECT id FROM Artist WHERE name=?''',(artist,))
artist_id=cur.fetchone()[0]
conn.commit()

I expect that I could fetch the first value of the extracted row, Which is the id.

bruno desthuilliers
  • 75,974
  • 6
  • 88
  • 118
ZIHONG XU
  • 1
  • 1

1 Answers1

0

The error you get means that cur.fetchone() returned None. This happens when the last select statement didn't yield any result (nothing matched the select statement).

So the question is "why didn't the select statement select anything when I just inserted something", and the answer is (well, most probably) that your transaction's isolation level prevents you from reading yet uncommited changes.

You could change the isolation level, but a simplest solution would be to first commit the transaction and only then try to read the data (IOW : move your conn.commit() statement between the "insert" and the "select").

But for this exact use case, you actually don't need the "select" query at all - you can just retrieve the last insert id directly.

bruno desthuilliers
  • 75,974
  • 6
  • 88
  • 118