I have a function like the below to get data from SQLite3 table.
def remedysql(crop, disease):
try:
conn = sqlite3.connect('plant_protection.db')
mycur = conn.cursor()
sql=f'select remedy from pp_remedy WHERE crop="{crop}" and disease="{disease}"'
#remedy = mycur.execute(sql).fetchone()[0]
mycur.execute(sql)
remedy = mycur.fetchone()[0]
return remedy
except sqlite3.Error as error:
print("Error while connecting to sqlite plantprot DB")
For the combination of "crop" and "disease", there will only be one record or none. The above function works fine when I give fetchone()[0]
, but does not work when I give only fetchone()
without [0]
.
Also please advise how to handle the NoneType
(no record) exception here.
From the doc:
The return value is a tuple, so
remedy
will be found at the first element, i.e.fetchone()[0]
. In the case where the query returnsNone
, there is no 0th element, so program will give a TypeError.One solution would be to use
fetchone()
and make sure it has returned a row before accessing the index. E.G.