MySQLdb._exceptions.ProgrammingError

MySQLdb._exceptions.ProgrammingError

这是我的源代码:

@app.route('/pythonlogin/register', methods=['GET', 'POST'])
def register():
    # Output message if something goes wrong...
    msg = ''
    # Check if "username", "password" and "email" POST requests exist (user submitted form)
    if request.method == 'POST' and 'username' in request.form and 'password' in request.form and 'email' in request.form:
        # Create variables for easy access
        username = request.form['username']
        password = request.form['password']
        email = request.form['email']
                # Check if account exists using MySQL
        cursor = mysql.connection.cursor(MySQLdb.cursors.DictCursor)
        cursor.execute("SELECT * FROM accounts WHERE username = %s", (username))
        account = cursor.fetchone()
        # If account exists show error and validation checks
        if account:
            msg = 'Account already exists!'
        elif not re.match(r'[^@]+@[^@]+\.[^@]+', email):
            msg = 'Invalid email address!'
        elif not re.match(r'[A-Za-z0-9]+', username):
            msg = 'Username must contain only characters and numbers!'
        elif not username or not password or not email:
            msg = 'Please fill out the form!'
        else:
            # Account doesnt exists and the form data is valid, now insert new account into accounts table
            cursor.execute("INSERT INTO accounts VALUES (NULL, %s, %s, %s)", (username, password, email))
            mysql.connection.commit()
            msg = 'You have successfully registered!'
    elif request.method == 'POST':
        # Form is empty... (no POST data)
        msg = 'Please fill out the form!'
    # Show registration form with message (if any)
    return render_template('register.html', msg=msg)

我不明白为什么我会收到这个错误,我的登录工作正常但我的注册有那个小问题,我在 myswl 服务器中 运行 感谢您的时间

您的第一个查询有一个小问题。

cursor.execute("SELECT * FROM accounts WHERE username = %s", (username))

它的作用是解压缩作为第二个参数传递的值并将其放入您的查询中,通常使用元组完成。现在这似乎是您想要的,但是这里缺少一个次要但非常重要的部分。具有一个值 的元组需要 尾随逗号,即 (username,) 否则它只是字符串周围的括号。因此,您的字符串实际上正在被解压缩,并且每个字符都作为参数传递给您的查询!

TL;DR

您需要在查询中添加尾随逗号以传递元组而不是字符串作为参数。

cursor.execute("SELECT * FROM accounts WHERE username = %s", (username,))