错误 1064 sql 语法错误

Error 1064 sql syntax error

我正在尝试使用 WTF 表单进行注册,但当我尝试通过 flask 执行注入数据时遇到 sql 语法错误。但我可以通过 mysql 命令行使用正常 sql 查询插入数据。

from wtforms import Form, BooleanField, StringField, PasswordField, validators
from MySQLdb import escape_string as thwart

class RegistrationForm(Form):
    username = StringField('Username', [validators.Length(min=4, max=25)])
    email = StringField('Email Address', [validators.Length(min=6, max=35)])
    password = PasswordField('New Password', [validators.DataRequired(), validators.EqualTo('confirm', message='Passwords must match')])
    confirm = PasswordField('Repeat Password')
    accept_tos = BooleanField('I accept the TOS', [validators.DataRequired()])
# for registering the user
@app.route('/register/', methods = ['GET', 'POST'])
def register_page():
    try:
        form = RegistrationForm(request.form)
        if request.method == 'POST' and form.validate():
            username = form.username.data
            email = form.email.data
            password = sha256_crypt.encrypt(str(form.password.data))

            c, conn = connection()
            x = c.execute("SELECT * FROM users WHERE username = '(%s)'" %(thwart(username),))
            #x = c.fetchone()
            if int(x) > 0:
                flash ("that username already taken, please take another")
                return render_template("register.html", form =form)
            else:
                c.execute("INSERT INTO users (username, password, email, tracking) VALUES (%s, %s, %s, %s)" %(thwart(username), thwart(password), thwart(email), thwart('/home/')))
                c.commit()
                flash("Thanks for registering")
                c.close()
                conn.close()
                gc.collect()

                session['logged_in'] = True
                session['username'] = username
                return redirect(url_for('dashboard'))


        return render_template("register.html", form = form)
    except Exception as e:
        return render_template("register.html", error = e, form = form)

错误可以在下面找到 输入密码并匹配确认后提交。我收到一个错误。谁能帮我解决这个问题。

您的 SQLite 语句看起来不对。

x = c.execute("SELECT * FROM users WHERE username = '(%s)'" %(thwart(username),))

据我所知,单引号已经被处理了,但无论如何你可以只使用准备好的语句:

x = c.execute("SELECT * FROM users WHERE username = ?", (thwart(username)))

关于您的 INSERT 声明也是如此:

c.execute("INSERT INTO users (username, password, email, tracking) VALUES (?, ?, ?, ?)" (thwart(username), thwart(password), thwart(email), thwart('/home/')))
            c.
query = "SELECT * FROM users WHERE username = %s"
x = c.execute(query, (thwart(username),))

同样

query2 = "INSERT INTO users (username, password, email, tracking) VALUES (%s, %s, %s, %s)"

c.execute(query2, (thwart(username), thwart(password), thwart(email), thwart('/home/'))

成功了!