开发者

how to count value returned from select query in python

I want to count the total number o开发者_StackOverflow社区f 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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜