繁体   English   中英

SQLite Python 中没有返回类型

[英]SQLite no return type in 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/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!"

选项 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]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM