2017-10-08 120 views
0

我希望我的代碼使用if語句來檢查用戶所在的用戶組,然後爲每個用戶調用不同的函數。我當前的代碼如下:SQLite3記錄驗證

c.execute('SELECT * from users WHERE username=? AND password =?', 
       (username_input, password_input)) 
    if c.fetchone() is not None: 
     c.execute('SELECT usergroup from users WHERE username=? AND password=?', 
           (username_input, password_input)) 
     user_group = c.fetchone() 
     for (usergroup,) in c: 
      if user_group == 1: 
       App.admin_login_successful(self) 
      elif user_group == 2: 
       App.user_login_successful(self) 
      else: 
       App.user_login_successful(self) 
       # This shouldn't happen, as all records should theoretically contain a value for usergroup. 

我應該怎麼做,使比較工作,我的記錄確實包含的值是1或2,但驗證不工作。

+0

你從''之前在C(用戶組)'打印(USER_GROUP)得到什麼:'?我不確定你爲什麼要在你的for循環中創建一個元組。 – roganjosh

+0

我爲(usergroup,)做了c:關閉其他用戶在這裏的建議以防止SQL注入,但他的回答並不是非常清楚。當我打印時,我得到('2',) –

+0

您正在從您的數據庫中檢索一些東西,所以如果要進行SQL注入,它已經發生了;我不確定這個建議是否有意義,或者是因爲這個建議不符合上下文。擺脫'for'循環(你使用'fetchone()',所以你只能得到1個結果),並將'if' /'elif'檢查改爲'if int(user_group [0])== 1:'etc 。 – roganjosh

回答

0

不要多次重複相同的sql查詢。

funcmap = {1: self.admin_login_successful, 2: self.user_login_successful} 
c.execute('SELECT usergroup from users WHERE username=? AND password=?', 
      (username_input, password_input)) 
for (usergroup,) in c: 
    funcmap[usergroup]() 

如果查詢沒有返回用戶組,然後for循環不會 執行其身。如果usergroup不是1或2,則 funcmap[usergroup]將增加KeyError。正如你所說,這個 不應該發生,但如果它KeyError會讓你 知道。你可能希望使用try..except KeyError聲明 各地funcmap[usergroup]()來處理一些其他方式的錯誤(日誌記錄,在退出之前更好的特定錯誤消息,等等),這取決於你如何實例化的sqlite3連接

注意,你怎麼設置up數據庫表,usergroup可能是一個整數或字符串。如果它返回一個字符串,你可能想問另一個關於如何檢索usergroup作爲整數的問題。 或者,你可以改變funcmap期望字符串作爲字典鍵:

funcmap = {'1': self.admin_login_successful, '2': self.user_login_successful}