2011-06-08 28 views
2

我試圖做到這一點的解釋,我可以得到它的工作,但我的函數內部它不爲什麼這一工作沒有(sqlite的,蟒蛇)

我想要做的事:

cursor = dbconnect.cursor() 
cursor.execute("""SELECT * FROM credits WHERE phone = ?""",(phone,)) 
data = cursor.fetchone() 
firstname = data[1] #the db is set as firstname in position 1 after the id(primekey) 

我用這個方法只是用不同的變量

的錯誤,當我做它的函數裏面我得到實際提取的所有數據:

firstname = data[1] 
TypeError: 'NoneType' object is not subscriptable 

作爲一個說明:我把打印語句中的數據對象之後,再看看它是返回,在返回的元組我在尋找解釋,在函數內部它返回 「無」

全碼:

def FindByPhone(self,phone): 
    '''Find Credit by phone number ONLY'''  
    dbconnect = sqlite3.connect(self.dbname) 
    cursor = dbconnect.cursor() 
    cursor.execute("""SELECT * FROM credits WHERE phone = ?""",(phone,)) 
    data = cursor.fetchone() 
    first = data[1] 
    last = data[2] 
    phone = data[3] 
    credit = data[4] 
    cid = data[0] 
    self.SetVariables(first,last,phone,credit,cid) 
    cursor.close() 
    dbconnect.close() 
    return 

回答

2

我認爲問題是,你的函數不檢查是否有數據庫匹配行。如果返回沒有記錄,您將收到此錯誤:

#!/usr/bin/python 
try: 
    import sqlite3 
except: 
    from pysqlite2 import dbapi2 as sqlite3 

#prepare testcase  
db="/tmp/soverflow.sqlite" 
dbconnect = sqlite3.connect(db) 
c = dbconnect.cursor() 
c.execute("""create table credits 
(id int not null primary key, firstname varchar(50), phone varchar(30),amount int not null)""") 
c.execute("""INSERT INTO credits (id,firstname,phone,amount) VALUES (1,'guybrush','123-456',24)""") 
c.execute("""INSERT INTO credits (id,firstname, phone,amount) VALUES (2,'elaine','1337-1337',18)""") 
dbconnect.commit() 
c.close() 


def print_firstname(phone): 
    cursor = dbconnect.cursor() 
    cursor.execute("""SELECT * FROM credits WHERE phone = ?""",(phone,)) 
    data = cursor.fetchone() 
    firstname = data[1] 
    cursor.close() # cleanup 
    print firstname 

print "testing existing row" 
print_firstname('1337-1337') 

print "testing missing row" 
print_firstname('nothere') 

=>

./soverflow_sqlite.py 
testing existing row 
elaine 
testing missing row 
Traceback (most recent call last): 
    File "./soverflow_sqlite.py", line 31, in <module> 
    print_firstname('not-in-db') 
    File "./soverflow_sqlite.py", line 23, in print_firstname 
    firstname = data[1] 
TypeError: 'NoneType' object is not subscriptable 

解決方案: 添加一個檢查,如果有一個從您的查詢返回的行

+0

我剛剛添加的實際的代碼即時嘗試運行在我原來的帖子 – Isov5 2011-06-08 06:40:34

+0

你到底怎麼稱呼你的功能?也許手機價值本身是無或數據庫中不存在的值? – Gryphius 2011-06-08 06:47:45

+0

嗯,我打電話給它的GUI wx.TextCtrl,我設置爲一個變量...像phone = wx.TextCtrl.GetValue() – Isov5 2011-06-08 06:55:49