[英]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.