2013-10-04 55 views
6

獲取此查詢返回的數字或行的正確方法是什麼?我專門查看是否沒有結果返回。獲取psycopg2數(*)結果數

sql = 'SELECT count(*) from table WHERE guid = %s;' 
data=[guid] 
cur.execute(sql,data) 
results = cur.fetchone() 
for r in results: 
    print type(r) # Returns as string {'count': 0L} Or {'count': 1L} 

謝謝。

+0

工作count將只返回1行(在這種情況下) –

+0

'type(r)'將不會**返回爲'{'count':0L}'。很可能它會打印''或類似的東西。 –

+0

類型(r)直接從控制檯返回{'count':0L}。 – Matt

回答

12

results本身就是一個行對象,在你的情況下(由聲稱的print輸出判斷),一個字典(你可能配置了dict-like cursor subclass);只需訪問count鍵:

result = cur.fetchone() 
print result['count'] 

因爲使用.fetchone()只有一行返回,而不是行的列表。

如果使用的字典(類似的)行光標,行是元組和計數值的第一個值:

result = cur.fetchone() 
print result[0] 
+0

謝謝。我盯着這個太久了,被type()返回一個字符串拋出。再次感謝! – Matt

1

下面我

cur.execute('select count(*) from table where guid = %s;',[guid]) 
rows = cur.fetchall() 
print 'ResultCount = %d' % len(rows)