2011-08-11 36 views
0

我想知道在使用python時是否從SQLite查詢返回了某個值。SQLite在Python中沒有返回類型

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塊中,有沒有辦法知道數據庫是否返回了某些內容。

此外,我知道我可以發出額外的查詢,但這會使連接過於健談。

回答

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:使用​​返回值。它包含結果中的行數。

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]