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.
The basic SQL standard query to count the rows in a table is: SELECT count(*) FROM table_name; This can be rather slow because PostgreSQL has to check visibility for all rows, due to the MVCC model.
In this form, the COUNT(DISTINCT column) returns the number of unique non-null values in the column. We often use the COUNT() function with the GROUP BY clause to return the number of items for each group. For example, we can use the COUNT() with the GROUP BY clause to return the number of films in each film category.
The PostgreSQL COUNT function counts a number of rows or non-NULL values against a specific column from a table. When an asterisk(*) is used with count function the total number of rows returns. Syntax: COUNT (* | [DISTINCT] ALL | column_name) Parameters.
In order to make sure a connection is still valid, read the property connection. isolation_level . This will raise an OperationalError with pgcode == "57P01" in case the connection is dead. This adds a bit of latency for a roundtrip to the database but should be preferable to a SELECT 1 or similar.
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:
result = cur.fetchone() print result['count']
Because you used .fetchone()
only one row is returned, not a list of rows.
If you are not using a dict(-like) row cursor, rows are tuples and the count value is the first value:
result = cur.fetchone() print result[0]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With