这是我的源代码:
@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服务器上运行,谢谢您的时间。
发布于 2020-01-11 17:37:07
您的第一个查询有一个小问题。
cursor.execute("SELECT * FROM accounts WHERE username = %s", (username))
这样做的是解压缩作为第二个参数传递的值,并将其放置到查询中,通常使用元组来完成。现在,这似乎是你的意图,然而,有一个小,但非常重要的一块缺失在这里。一个值为的元组需要一个尾随逗号,即(username,),否则,它只是字符串周围的方括号。因此,您的字符串实际上正在被解压缩,每个字符都作为参数传递给您的查询!
TL;DR
您需要在查询中添加一个后缀逗号,以传递元组,而不是作为参数的字符串。
cursor.execute("SELECT * FROM accounts WHERE username = %s", (username,))
https://stackoverflow.com/questions/59696466
复制相似问题