I tried to do this in the interpreter and I can get it to work but inside my function it doesn'开发者_运维问答t
What I'm trying to do:
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)
I'm actually extracting all the data using this method just with different variables
The Error I get when I do it inside the function:
firstname = data[1]
TypeError: 'NoneType' object is not subscriptable
As a note: I put a print statement after the data object to see what it was returning, in the interpreter it returns the tuple i'm searching for, inside the function it's returning 'None'
FULL CODE:
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
I think the problem is that your function doesn't check if there was a matching row in the database. you will get this error if no row is being returned:
#!/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
Solution: Add a check if there was a row returned from your query
精彩评论