2017-01-30 173 views
1

enter image description here我想尝试使用WTF表单注册,并且当我试图通过瓶子执行注入数据时,我正面临sql语法错误。但我可以使用普通的sql查询通过mysql命令行插入数据。错误1064 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) 

错误可以在下面 发现输入密码并确认与匹配,并提出申请后。我收到一个错误。任何人都可以请帮我。

回答

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

工作!

1

你的SQLite语句看起来不对。

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

单引号已经被据我所知处理,但在任何情况下,你可以只使用一个事先准备好的声明:关于你的INSERT声明

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

也是如此:

c.execute("INSERT INTO users (username, password, email, tracking) VALUES (?, ?, ?, ?)" (thwart(username), thwart(password), thwart(email), thwart('/home/'))) 
      c. 
+0

这工作。但是我得到一个新的错误,称为'str'对象在实现此代码后无法调用。 @Tim Biegeleisen – Bhargav

+0

你能给我一个行号,至少在发生错误的地方? –

+0

'password = sha256_crypt.encrypt(str(form.password.data))'......你确定你的代码没有其他问题吗? –