0

I am implementing the subtraction from the user's cash and I can't figure out a way to insert variables into my sql statement. The variables are numbers here.

Here is my code:

if user_cash > total_price:
        db.execute('UPDATE users SET cash = %d - %d WHERE id = 1', user_cash, total_price)

I get this error:

RuntimeError: 'int' object has no attribute 'key'

I tried using '?' instead of '%d', but the result is the same. What might cause it? Help me, please.

Thanks!

1

Review the Notes section of week9, or week 9 lecture starting around 1:10:30 to see how parameter substitution (placeholders) is handled with the execute method.

Now in register we’ll have similar code as before, but if we have data to save, we can actually save it with db.execute("INSERT INTO registrants (name, dorm) VALUES(:name, :dorm)", name=request.form["name"], dorm=request.form["dorm"]). We see the query as the first argument to db.execute, and we use :name and :dorm as placeholders, since we want to replace them with the value of variables. So the next arguments pass in those values from request.form. Then the cs50 execute function will substitute those values into the final SQL query.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .