How are you supposed to handle exceptions when there are no rows for this id. How should the calling code handle this
def function(id)
mysql_conn = MySQLdb.connect(..)
cursor = mysql_conn.cursor()
cursor.execute("""select val from fooo where id = %s""", (id))
row = cursor.fetchone()
return row[0]
Whenever I find myself fetching just one row I always like to use the following (although not the best performance wise) construct.
This effectively returns when the first iteration of the loop runs. Which can only happen if there is at least
1row in the result set. And otherwise will run the code behind theforloop.You can raise a custom exception, or return a special value such as
Nonethat lets the calling function know nicely that there were no rows.