Bitcoin Forum
June 15, 2024, 02:29:10 PM *
News: Latest Bitcoin Core release: 27.0 [Torrent]
 
   Home   Help Search Login Register More  
Pages: [1]
  Print  
Author Topic: n00b python db question  (Read 475 times)
AliceWonderMiscreations (OP)
Full Member
***
Offline Offline

Activity: 182
Merit: 107


View Profile WWW
January 31, 2016, 04:24:49 AM
 #1

Code:
cursor.execute("SELECT max(tstamp) AS tstamp FROM ratedata");
rows = cursor.fetchall()
if rows:
        print "There were rows"
else:
        print "There were no rows"

It seems python counts the result "none" as a row. So even if the database is empty and there is no max(tstamp) for it to select, it still seems to think there is a row.

This is different from the PDO behaviour in PHP that I am use to.

How, in python, do you determine the result of a query is an empty set?

I must have looked at least 20 different tutorials online and every damn one of them uses examples where there are results to the query.

Thanks for the solution

I hereby reserve the right to sometimes be wrong
AliceWonderMiscreations (OP)
Full Member
***
Offline Offline

Activity: 182
Merit: 107


View Profile WWW
January 31, 2016, 05:11:05 AM
 #2

I think this is what is confusing python -
Code:
MariaDB [tstbtcart]> SELECT max(tstamp) AS tstamp FROM ratedata;
+--------+
| tstamp |
+--------+
|   NULL |
+--------+
1 row in set (0.00 sec)

MariaDB [tstbtcart]>

It seems to be interpreting NULL as a result row even in the CLI client. With PDO driver in PHP it does not.

When I ask python to print the row the result is
Code:
(None,)

which is different from NULL and I am guessing it is the driver that does that.

In cases where MySQL returns NULL is there a way in python to detect that opposed to it returning a result?

With SELECT max(foo) it looks like the row count will always be 1 whether or not the result is null (because no records exist) or has a value.

I hereby reserve the right to sometimes be wrong
AliceWonderMiscreations (OP)
Full Member
***
Offline Offline

Activity: 182
Merit: 107


View Profile WWW
January 31, 2016, 05:27:32 AM
 #3

This works around the issue:
Code:
cursor.execute("SELECT COALESCE(max(tstamp), 0) FROM ratedata");

I hereby reserve the right to sometimes be wrong
AliceWonderMiscreations (OP)
Full Member
***
Offline Offline

Activity: 182
Merit: 107


View Profile WWW
January 31, 2016, 06:24:17 AM
 #4

I'm all squared away now. It seems the MySQL bindings in python are a lot more primitive than PDO in PHP. I guess I've been spoiled.

I hereby reserve the right to sometimes be wrong
Pages: [1]
  Print  
 
Jump to:  

Powered by MySQL Powered by PHP Powered by SMF 1.1.19 | SMF © 2006-2009, Simple Machines Valid XHTML 1.0! Valid CSS!