SQLite/Flask - 行值被滥用

Posted

技术标签:

【中文标题】SQLite/Flask - 行值被滥用【英文标题】:SQLite/Flask - Row Value Misused 【发布时间】:2020-10-18 19:35:25 【问题描述】:

我正在尝试查询一个应该保存用户股票的表。如果找到该用户拥有的股票的结果,则在购买订单后使用新的股票数量对其进行更新。如果用户尚未拥有该股票,请将其添加到表中。

我在stockcheck = db.execute("SELECT * FROM holdings WHERE (userID = :userid, symbol = :symbol)", userid=session["user_id"], symbol=symbol) 遇到了一个错误,我不确定“滥用行值”是什么意思。在错误中,它显示了它正在搜索的正确信息(我的用户 ID 和股票代码),所以不确定发生了什么。一如既往地感谢您的帮助!

代码:

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

    if request.method == "GET":
        return render_template("/buy.html")
    else:

        # collect user input - symbol
        symbol = request.form.get("symbol").upper()

        # if input is blank or symbol doesn't exist, return apology
        if not symbol:
            return apology("You must enter a stock symbol.", 300)

        # collect user input - # of shares
        shares = int(request.form.get("shares"))

        # if blank or not a positive integer, return apology
        if not shares:
            return apology("Enter a valid number of shares.", 300)

        # pull current price info from API
        quote = lookup(symbol)
        shareprice = quote["price"]
        totalprice = shareprice * shares

        # check users table to see how much cash user has
        cashcheck = db.execute("SELECT cash FROM users WHERE id = :userid", userid = session["user_id"])

        cash = cashcheck[0]["cash"]

        if cash >= totalprice:
            # in transactions table, insert userID, symbol, shares, shareprice, and totalprice
            # transID should be autogenerated and autoincremented.  date is also autofilled by SQLite.
            db.execute("INSERT INTO transactions (userID, symbol, shares, shareprice, totalprice) VALUES (:userid, :symbol, :shares, :shareprice, :totalprice)",
            userid=session["user_id"], symbol=symbol, shares=shares, shareprice=shareprice, totalprice=totalprice)

            cash = cash - totalprice

            # update cash balance
            db.execute("UPDATE users SET cash = :cash WHERE id = :userid", cash=cash, userid=session["user_id"])

            # update holdings table
            # check if stock exists, if so update with new shares
            stockcheck = db.execute("SELECT * FROM holdings WHERE (userID = :userid, symbol = :symbol)", userid=session["user_id"], symbol=symbol)

            if stockcheck[0] > 0:
                newshares = stockcheck[0] + shares
                db.execute("UPDATE shares FROM holdings SET shares = :newshares WHERE (userID = :userid, symbol = :symbol)", newshares=newshares, userID=session["user_id"], symbol=symbol)
            else:
                # else, create stock and add shares
                db.execute("INSERT INTO holdings (userID, symbol, shares) VALUES (:userID, :symbol, :shares)", userID=session["user_id"], symbol=symbol, shares=shares)

            #return index
            return redirect("/")
        else:
            # else, return apology (not enough cash)
            return apology("Not enough cash balance to make execute this order.", 300)

错误:

DEBUG:cs50:SELECT * FROM holdings WHERE (userID = 4, symbol = 'F')
ERROR:application:Exception on /buy [POST]
Traceback (most recent call last):
  File "/usr/local/lib/python3.7/site-packages/flask/app.py", line 2446, in wsgi_app
    response = self.full_dispatch_request()
  File "/usr/local/lib/python3.7/site-packages/flask/app.py", line 1951, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "/usr/local/lib/python3.7/site-packages/flask/app.py", line 1820, in handle_user_exception
    reraise(exc_type, exc_value, tb)
  File "/usr/local/lib/python3.7/site-packages/flask/_compat.py", line 39, in reraise
    raise value
  File "/usr/local/lib/python3.7/site-packages/flask/app.py", line 1949, in full_dispatch_request
    rv = self.dispatch_request()
  File "/usr/local/lib/python3.7/site-packages/flask/app.py", line 1935, in dispatch_request
    return self.view_functions[rule.endpoint](**req.view_args)
  File "/home/ubuntu/finance/helpers.py", line 34, in decorated_function
    return f(*args, **kwargs)
  File "/home/ubuntu/finance/application.py", line 96, in buy
    stockcheck = db.execute("SELECT * FROM holdings WHERE (userID = :userid, symbol = :symbol)", userid=session["user_id"], symbol=symbol)
  File "/usr/local/lib/python3.7/site-packages/cs50/sql.py", line 21, in decorator
    return f(*args, **kwargs)
  File "/usr/local/lib/python3.7/site-packages/cs50/sql.py", line 372, in execute
    raise e
RuntimeError: row value misused

【问题讨论】:

您是否尝试从 (userID = :userid, symbol = :symbol) 中删除括号?另外我不太确定您是否需要在两个条件之间使用 AND/OR 运算符而不是逗号。 修复它的是 AND 运算符而不是逗号。谢谢! 【参考方案1】:

当使用 WHERE 子句指定多个条件时,必须使用 AND 或 OR 而不是逗号来分隔条件:

stockcheck = db.execute("SELECT * FROM holdings WHERE (userID = :userid AND symbol = :symbol)", userid=session["user_id"], symbol=symbol)

【讨论】:

这就是我们所需要的。到下一个错误大声笑 很高兴能帮上忙!我去年做了这个项目,真的学到了很多。【参考方案2】:

您的查询未正确编写。你要的是where userid = 4 and symbol='F'

sqlite> create table users (cash int, userid int, symbol text);
sqlite> select * from users;
sqlite> insert into users values (10, 1, 'SWHC');
sqlite> select * from users;
10|1|SWHC
sqlite> select * from users where userid = 1 and symbol = 'SWHC';
10|1|SWHC
sqlite> select * from users where (userid = 1, symbol = 'SWHC');
SQL error: near ",": syntax error
sqlite> 

【讨论】:

以上是关于SQLite/Flask - 行值被滥用的主要内容,如果未能解决你的问题,请参考以下文章

(sqlite,Flask + React),flask session session.get() 返回 None [重复]

安卓应用版本升级时sqlit数据库升级

Python与sqlit数据库--简单介绍

busybox filesystem httpd php-5.5.31 sqlit3 webserver

sqlit3事务

Sqlit--学习教程(简介)