Python 获取 psycopg2 count(*) 结果数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19191766/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get psycopg2 count(*) number of results
提问by Matt
Whats the correct way to get the number or rows returned by this query? I'm specifically looking to see if no results are returned.
获取此查询返回的数字或行的正确方法是什么?我特别想看看是否没有返回结果。
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}
Thanks.
谢谢。
采纳答案by Martijn Pieters
results
is itself a row object, in your case (judging by the claimed print
output), a dictionary (you probably configured a dict-like cursor subclass); simply access the count
key:
results
本身就是一个行对象,在你的情况下(根据声称的print
输出判断),一个字典(你可能配置了一个类似 dict 的游标子类);只需访问count
密钥:
result = cur.fetchone()
print result['count']
Because you used .fetchone()
only one row is returned, not a list of rows.
因为你.fetchone()
只使用了一行返回,而不是行列表。
If you are notusing a dict(-like) row cursor, rows are tuples and the count value is the first value:
如果您不使用 dict(-like) 行游标,则行是元组,计数值是第一个值:
result = cur.fetchone()
print result[0]
回答by alejandro
The following worked for me
以下对我有用
cur.execute('select * from table where guid = %s;',[guid])
rows = cur.fetchall()
print 'ResultCount = %d' % len(rows)
Drawback:This will not be very efficient for the DBMS if allyou need is the count.
缺点:如果这会不会是对DBMS非常高效所有你需要的是计数。