2017-01-30 105 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))'......你確定你的代碼沒有其他問題嗎? –