在python 3中的选择查询上使用fetchone,语法混乱

时间:2018-09-21 16:19:20

标签: python sqlite

我正在尝试在我的站点上设置注册功能,但我坚持设置查询数据库以查看用户名是否存在的逻辑。如果这样做,应该返回道歉页面。

这是我的代码:

@app.route("/register", methods=["GET", "POST"])
def register():
    """Register user"""

    # User reached route via POST (as by submitting a form via POST)
    if request.method == "POST":

        # Stored POST data to variables
        username = request.form.get('username')
        password = request.form.get('password')
        confirmation = request.form.get('confirmation')

        # Ensure username was submitted
        if not username:
           return apology("must provide username", 403)

        # Ensure password and confirmation were both submitted
        elif not password:
            return apology("must provide password in both fields", 403)

        # Ensure passwords match
        elif confirmation != password:
            return apology("passwords do not match", 403)

        elif db.execute('SELECT id FROM users WHERE username = ?', 
        (username,)).fetchone()  is not None:
            return apology("Username already exists", 403)

我不断收到此错误:

elif db.execute('SELECT id FROM users WHERE username = ?', 
(username,)).fetchone()  is not None:
TypeError: execute() takes 2 positional arguments but 3 were given

我在他们第一次使用cursor()方法的地方看到了代码,但是我认为execute()方法在python 3中做到了吗?谢谢您的帮助,我的数据库查询。

1 个答案:

答案 0 :(得分:0)

我意识到问题出在我的数据库连接上。因此.execute()语法与标准文档不同。

我更改了以下内容:

from cs50 import SQL; and
db = SQL("sqlite:///finance.db")

收件人:

import sqlite3; and
db = sqlite3.connect('finance.db')

希望这可以帮助世界上其他人使用相同的pset,而又不想使用缩写的CS50库。我上面的查询语句的语法正确。

    elif db.execute('SELECT id FROM users WHERE username = ?', 
    (username,)).fetchone()  is not None:
        return apology("Username already exists", 403)