I use SELECT COUNT(*) FROM db WHERE <expression> to see if a set of records is null. So:
>>> cnt = c.fetchone() >>> print cnt (0L,)
My question is: how do you test for this condition?
I have a number of other ways to accomplish this. Is something like the following possible?
if cnt==(0L,): # do something
fetchone returns a row, which is a sequence of columns.
If you want to get the first value in a sequence, you use .
You could instead compare the row to (0,), as you're suggesting. But as far as I know neither the general DB-API nor the specific MySQLdb library guarantee what kind of sequence a row is; it could be a list, or a custom sequence class. So, relying on the fact that it's a tuple is probably not a good idea. And, since it's just as easy to not do so, why not be safe and portable?
count_row = c.fetchone() count = count_row if count == 0: do_something()
Or, putting it together in one line:
if c.fetchone() == 0: do_something()
本文出自 Suzf Blog。 如未注明，均为 SUZF.NET 原创。