[英]SQLite no return type in Python
I am trying to find a way to know whether or not some value was returned from an SQLite query when using 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]
If the table does contain a matching value, then it will be stored in returnObject
.如果表确实包含匹配值,那么它将存储在
returnObject
中。
The problem happens in the case that the database doesn't have any entries matching the request.问题发生在数据库没有与请求匹配的任何条目的情况下。 In that case, I get a
exceptions.TypeError: unsubscriptable object
在这种情况下,我得到一个
exceptions.TypeError: unsubscriptable object
Besides placing this entire block in a try/expect block, is there a way of knowing whether or not something was returned by the database.除了将整个块放在 try/expect 块中之外,还有一种方法可以知道数据库是否返回了某些内容。
Also, I am aware that I could issue an extra query, but this would make the connection too chatty.另外,我知道我可以发出额外的查询,但这会使连接变得过于冗长。
You have a couple options, depending on your preferences.您有几个选择,具体取决于您的喜好。
Option 1 : check the value of returnObject before using it.选项 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!"
Option 2: use the return value of execute()
.选项 2:使用
execute()
的返回值。 It contains the number of rows in the result.它包含结果中的行数。
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]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.