我试图找到一种方法来了解使用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]
Run Code Online (Sandbox Code Playgroud)
如果表确实包含匹配值,那么它将存储在returnObject.
如果数据库没有与请求匹配的任何条目,则会出现问题.在那种情况下,我得到一个exceptions.TypeError: unsubscriptable object
除了将整个块放在try/expect块中之外,还有一种方法可以知道数据库是否返回了某些内容.
此外,我知道我可以发出额外的查询,但这会使连接过于繁琐.
根据您的偏好,您有几种选择.
选项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!"
Run Code Online (Sandbox Code Playgroud)
选项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]
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3005 次 |
| 最近记录: |