2012-04-03 144 views
3

我有一個寫入數據庫的方法,用戶名和密碼的用戶誰希望註冊。在存儲他們提供給數據庫的用戶名和密碼之前,我想檢查他們選擇的用戶名是否已經存在於「未決」列表或已批准的「聯繫人」列表中。Python和SQLite:檢查數據庫中是否存在項目?

這裏是我以前做的代碼:

@cherrypy.expose 
def writePending(self, username=None, password=None, message=None, signin=None): 
    """ Add request of friendship into a database which stores all 
     pending friendships. 
    """ 

    page = get_file(staticfolder + "/html/friendingPage.html") 

    if username != "" and password != "" and message !="": 
     con = lite.connect('static/database/Friendship.db') 
     cur = con.cursor() 

     with con:  
      cur.execute("CREATE TABLE IF NOT EXISTS pending(user TEXT, pass TEXT, info TEXT)") 
      cur.execute("CREATE TABLE IF NOT EXISTS contacts(user TEXT, pass TEXT)") 

      "Check to see if the username is already registered" 

      cur.execute("Select * from pending where user = ?", (username,)) 
      check1=cur.fetchone() 
      cur.execute("Select * from contacts where user = ?", (username,)) 
      check2=cur.fetchone() 

      if check1[0] != None: 
       page = page.replace("$Error", "The ID you used is still pending for friendship") 
      elif check2[0] != None: 
       page = page.replace("$Error", "The ID you used is already added as a contact") 
      else: 
       cur.execute("CREATE TABLE IF NOT EXISTS pending(user TEXT, pass TEXT, info TEXT)") 
       cur.execute("INSERT INTO pending VALUES(?, ?, ?)", (username, password, message))    
       page = get_file(staticfolder + "/html/thankYouPage.html") 

    else: 
     page = get_file(staticfolder + "/html/friendingPage.html") 
     page = page.replace("$Error", "You Must fill out all fields to proceed") 

    return page 

不過,我會得到那個

Traceback (most recent call last): 
    File "/usr/lib/pymodules/python2.7/cherrypy/_cprequest.py", line 606, in respond 
    cherrypy.response.body = self.handler() 
    File "/usr/lib/pymodules/python2.7/cherrypy/_cpdispatch.py", line 25, in __call__ 
    return self.callable(*self.args, **self.kwargs) 
    File "proj1base.py", line 540, in writePending 
    if type(check1[0]) != None: 
TypeError: 'NoneType' object is not subscriptable 

我想知道我能做些什麼,以避免消息?

謝謝。

回答

6

在你的例子中,check1將是None,所以你不能使用[0]就可以了。你可以做這樣的事情:

if check1 is not None: 
    (error response) 

或改爲只使用cur.rowcount代替cur.fetchone()

if cur.rowcount > 0: 
    (error response) 
1

fetchone()回報None如果沒有一行。你可以這樣編碼:

if check1: 
    ...do something with check1, like check1[0]... 
else: 
    .. means no row 
相關問題