How to select Count(*) with Python and mysql.Nector

Asked

Viewed 419 times

3

The library I’m using is that one.

That is the code:

cur.execute("""SELECT COUNT(*) as total FROM tabela as t WHERE ... """, (v1, v2))

for (total) in cur:
    if total > 0:
        print('Existe')

The problem is there’s never any value.

PS: There are data in the table to bring a count > 0

What’s wrong with that?

1 answer

2


Since it’s a Count you don’t need to use the for to get the data.

Another thing is that the total is not a whole, it is a tuple

Anyway do it like this:

cur.execute("""SELECT COUNT(*) as total FROM tabela as t WHERE ... """, (v1, v2))
(total,) = cursor.fetchone()
if total:
    ...

Browser other questions tagged

You are not signed in. Login or sign up in order to post.