简体   繁体   中英

how to count value returned from select query in python

I want to count the total number of rows returned by query. I am able to retrieved rows returned by query but what if i need to work in case when no data exits. that is when query returns no va from database.

the code i used to solve this problem is :

try: cur.execute(query)

    id = cur.fetchone()[0]
    if(id is None):
        return '-1'
    else: 
        return id

But this doenst help when no values is returned selected from query.(when condition doesnt meet criteria defined in select statement)

cur.fetchall() will give you a sequence of all the rows. You can look at the length of that sequence to see if any rows were returned. This works for small result sets, but may not be ideal for queries that return large amounts of data.

Alternatively, you can look at cur.rowcount . Rowcount will return the number of rows in the query, or -1 if the number cannot be determined. It is up to the implementation to set rowcount; several popular python database modules (most notably sqlite3), do not set rowcount for all queries. For modules that do not set rowcount, the only way to count the number of result rows is to load the full result set into memory.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM