Get counter psycopg2 (*)

What is the correct way to get the number or rows returned by this query? I specifically look to see if the results are returning.

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.

+6
source share
2 answers

results itself is an object of a string in your case (judging by the declared output of print ), a dictionary (you probably configured a subclass of dict-like cursor ); just hit the count key:

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

Since you used .fetchone() , only one line is returned, not a list of lines.

If you are not using the dict (-like) line cursor, the rows are tuples, and the count value is the first value:

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

The following worked for me

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

Source: https://habr.com/ru/post/955278/


All Articles