错误1064 sql语法错误

时间:2017-01-30 04:31:50

标签: flask mysql-python

enter image description here我正在尝试使用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)

错误可以在下面找到 输入密码并将其与确认和提交相匹配。我收到了一个错误。任何人都可以帮助我。

2 个答案:

答案 0 :(得分:1)

您的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.

答案 1 :(得分:0)

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/'))

工作!