【发布时间】:2021-06-13 05:51:21
【问题描述】:
[
我正在尝试创建一个用于买卖股票的应用程序。如果我出售同一家公司的所有股票,我想删除该行而不是显示 0 股。 我不确定如何根据其值删除该行。
这里给了我错误不完整的输入:
db.execute("INSERT INTO stocks (user_id, symbol, name, shares, price, total_cost, transaction_type) VALUES(:user_id, :symbol, :name, :shares, :price, :total_cost, :transaction_type", user_id=user_id, name=name, symbol=symbol, shares= -1*shares, price=price, total_cost=total_cost, transaction_type=transaction_type)
这行代码在我添加删除条件之前就可以工作了。
@app.route("/sell", methods=["GET", "POST"])
@login_required
def sell():
"""Sell shares of stock"""
#Access the current user
user_id= session["user_id"]
if request.method =="POST":
if not request.form.get("symbol") or not request.form.get("shares"):
return apology("Enter a valid symbol or number of shares")
#Define data
symbol=request.form.get("symbol")
shares=int(request.form.get("shares"))
stock=lookup(symbol)
price=stock.get("price")
total_cost=int(shares)*stock["price"]
name=stock.get("name")
transaction_type="sale"
if stock is None:
return apology("Enter a valid symbol")
#Access existing data in DB
rows= db.execute("SELECT symbol, sum(shares) as shares FROM stocks WHERE user_id=:user_id GROUP BY symbol", user_id=user_id)
#Validate if the current user owns the shares they are trying to sell
for row in rows:
if row["symbol"]==symbol:
if shares > row["shares"]:
return apology("Enter a valid number of shares")
if row["shares"]-shares==0:
db.execute("DELETE FROM stocks WHERE user_id = :user_id AND symbol = :symbol",
symbol=symbol, user_id=session["user_id"])
user=db.execute("SELECT cash FROM users WHERE id=:user_id", user_id=user_id)
new_cash=user[0]["cash"]+total_cost
#Add transaction to the db
#Update DB cash of the user
db.execute ("UPDATE users SET cash=:new_cash WHERE id=:id", new_cash=new_cash, id=user_id)
db.execute("INSERT INTO stocks (user_id, symbol, name, shares, price, total_cost, transaction_type) VALUES(:user_id, :symbol, :name, :shares, :price, :total_cost, :transaction_type", user_id=user_id, name=name, symbol=symbol, shares= -1*shares, price=price, total_cost=total_cost, transaction_type=transaction_type)
return redirect("/")
else:
share_symbols=[]
symbs = db.execute("SELECT symbol FROM stocks WHERE user_id=:user_id GROUP BY symbol",
user_id=user_id)
for symb in symbs:
share_symbols.append(symb)
return render_template("sell.html", share_symbols=share_symbols)
【问题讨论】:
-
VALUES 子句缺少右括号。
-
谢谢。我一定是在尝试不同的选择时错过了它。我仍然无法删除该行并显示正确的数据。我在原始帖子中附上了屏幕截图。如果有人能就此提出建议,我将不胜感激。