SQLite在Python中没有返回类型
我正在寻找一种方法,想知道在使用Python进行SQLite查询时,是否有返回值。
conn = sqlite3.connect('/path/to/database.db')
cursor=conn.cursor()
t=(value,)
cursor.execute("select field from table where other_field = ?", t)
returnObject = cursor.fetchone()[0]
如果表中确实有匹配的值,那么这个值会被存储在returnObject
里。
问题出现在数据库没有任何与请求匹配的条目的情况下。在这种情况下,我会遇到一个exceptions.TypeError: unsubscriptable object
的错误。
除了把整个代码块放在一个try/except的结构里,还有没有其他方法可以知道数据库是否返回了结果。
另外,我知道我可以再发一个额外的查询,但这样会让连接变得太繁琐。
1 个回答
6
你有几个选择,可以根据自己的喜好来决定。
选项 1: 在使用 returnObject
之前,先检查一下它的值。
conn = sqlite3.connect('/path/to/database.db')
cursor=conn.cursor()
t=(value,)
cursor.execute("select field from table where other_field = ?", t)
returnObject = cursor.fetchone()
if returnObject:
print returnObject[0]
else:
print "Nothing found!"
选项 2: 使用 execute()
的返回值。这个返回值里包含了结果中的行数。
conn = sqlite3.connect('/path/to/database.db')
cursor=conn.cursor()
t=(value,)
rowCount = cursor.execute("select field from table where other_field = ?", t)
if rowCount > 0:
returnObject = cursor.fetchone()[0]