0

I'm getting RuntimeError: 'tuple' object has no attribute 'key'. I'm confused as to why this is. This is where the error is occurring.

transaction = db.execute("INSERT INTO transactions (user, stock, price) VALUES (?, ?, ?)", (username, symbol, amount))

This is weird because I've defined username, symbol, and amount as variables above. Below is my full code. What am I doing wrong?

@app.route("/buy", methods=["GET", "POST"])
@login_required
def buy():
    """Buy shares of stock."""

    if request.method == "POST":

        if not request.form.get("symbol"):
            return apology("must enter stock symbol")

        shares = int(request.form.get("shares"))

        if not shares:
            return apology("must enter number of shares")

        userdict = (db.execute("SELECT * FROM users WHERE id = 1"))[0]
        cash = userdict["cash"]
        username = userdict["username"]

        stock = lookup(request.form.get("symbol"))
        name = stock['name']
        symbol = stock['symbol']
        price = stock['price']

        amount = shares*price


        if cash > amount:
            transaction = db.execute("INSERT INTO transactions (user, stock, price) VALUES (?, ?, ?)", (username, symbol, amount))

    else:
        return render_template("buy.html")

    return apology("TODO")

1 Answer 1

2

That's not the right syntax for the execute method. (It woulda worked last term with mySQL).

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.

1
  • Thank you! It works now.
    – Ethan Teo
    Feb 21, 2017 at 3:37

You must log in to answer this question.

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