(sqlite3.OperationalError)表事务没有列 - Python

时间:2017-12-13 04:20:22

标签: python sqlite

我参加了一个在线课程,要求我建立一个Python和sqlite的股票交易网站。我收到以下错误:

sqlalchemy.exc.OperationalError: (sqlite3.OperationalError) table 
transactions has no column named purchase [SQL: "INSERT INTO 
transactions (username, symbol, price, quantity, purchase, timestamp) 
VALUES ('Ari', 'ZG', 40.39, 5, 201.95, '2017-12-13 03:58:52.905863');"]

如果您查看下面的代码以更新用户的交易历史记录,您会看到我将购买变量添加到SQL查询中,我也将其作为数据库中的列。< / p>

from cs50 import SQL
from flask import Flask, flash, redirect, render_template, request, session, url_for
from flask_session import Session
from passlib.apps import custom_app_context as pwd_context
from tempfile import mkdtemp
from datetime import datetime

from helpers import *

# configure application
app = Flask(__name__)

# ensure responses aren't cached
if app.config["DEBUG"]:
    @app.after_request
    def after_request(response):
        response.headers["Cache-Control"] = "no-cache, no-store, must-revalidate"
        response.headers["Expires"] = 0
        response.headers["Pragma"] = "no-cache"
        return response

# custom filter
app.jinja_env.filters["usd"] = usd

# configure session to use filesystem (instead of signed cookies)
app.config["SESSION_FILE_DIR"] = mkdtemp()
app.config["SESSION_PERMANENT"] = False
app.config["SESSION_TYPE"] = "filesystem"
Session(app)

# configure CS50 Library to use SQLite database
db = SQL("sqlite:///finance.db")

@app.route("/")
@login_required
def index():
    return apology("TODO")

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

    # if user reached route via POST (as by submitting a form via POST)
    if request.method == "GET":
        return render_template("buy.html")
    else:
        # ensure user entered a symbol and shares
        symbol = request.form.get("symbol")
        shares = request.form.get("shares")
        if not symbol or not shares:
            return apology("Must input stock ticker and shares")

        # check to make sure stock is real
        stock = lookup(request.form.get("symbol"))
        if not stock:
            return apology("Stock does not exist")

        # make sure user inputs valid number of shares
        shares = int(shares)
        if shares <= 0:
            return apology("Shares must be positive integer")

        # select user's cash balance
        rows = db.execute("SELECT * FROM users WHERE id = :id", id=session["user_id"])
        cash = float(rows[0]["cash"])

        # total cost of purchase
        purchase = float(stock["price"]*float(shares))

        # does user have enough cash?
        if cash < purchase:
            return apology("You don't have enough money")

        # update user cash
        db.execute("UPDATE users SET cash = cash - :purchase WHERE id = :id;", \
                    purchase=purchase, id=session["user_id"])

        # update user's transaction history
        db.execute("INSERT INTO transactions (username, symbol, price, quantity, purchase, timestamp) \
                    VALUES (:username, :symbol, :price, :quantity, :purchase, :timestamp);", \
                    username=rows[0]["username"], symbol=stock["symbol"], price=float(stock["price"]), \
                    quantity=shares, purchase=purchase, timestamp=str(datetime.now()))

        # return to index
        return redirect(url_for("index"))

以下是我的交易数据库结构的图像:

SQL transactions structure

你能帮我弄清楚我做错了吗?

提前致谢!

1 个答案:

答案 0 :(得分:0)

我刚刚在我的sqlite数据库中删除了事务表并重新实现了它。现在它有效。