为什么这不起作用(sqlite,python)

时间:2011-06-08 05:56:17

标签: python 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

作为注释:我在数据对象后面放了一个print语句来查看它返回的内容,在解释器中它返回我正在搜索的元组,在它返回的函数内部   '无'

完整代码:

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

1 个答案:

答案 0 :(得分: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

解决方案: 添加检查是否从查询中返回了一行