Index out of range/ conditional issues

62 Views Asked by At

So I'm trying to run a conditional that, based on the number of rows returned by an SQL query, determines whether or not I add a row to the same database or update an existing row. If the number of rows in my owned_stocks table is 0, that means that the user does not own stocks of this company and I add a row, and if the number is one then that means that the user already owns stocks and I just edit that existing row:

count = db.execute("SELECT COUNT (symbol) FROM owned_stocks WHERE user_id=? AND symbol=?", session["user_id"], symbol["symbol"])

        if count == 0:
            db.execute("INSERT INTO owned_stocks (symbol, current_price, stock_number, user_id) VALUES(?, ?, ?, ?)", symbol["symbol"], symbol["price"], buy_amount, session["user_id"])#!!
        else:
            user_amount_raw = db.execute("SELECT stock_number FROM owned_stocks WHERE symbol=? AND user_id=?", symbol["symbol"], session["user_id"])
            user_amount = int(user_amount_raw[0]["stock_number"])
            db.execute("UPDATE owned_stocks SET stock_number = ? WHERE id = ? AND symbol = ?", user_amount + buy_amount, session["user_id"], symbol)

But when I try this out on my program with a symbol that the user has no owned stocks of, the following error shows up:

    user_amount = int(user_amount_raw[0]["stock_number"])
    IndexError: list index out of range

Shouldn't my program be executing the first if clause? I tried running the SQL query by itself on a separate terminal to confirm that it returns a count of 0, and it does. What am I missing?

1

There are 1 best solutions below

0
Rick James On

You can probably switch to Upsert (INSERT ... ON DUPLICATE UPDATE ...) and simplify the code and speed up the code and avoid the problem.