tags:

views:

25

answers:

2

I am selecting the maximum date value from a MySQL database table in python using the MySQLdb module. If the result comes back as null, I want to override it with a default value. I could do this in the MySQL using a sub-query, but would prefer to do it in python.

Any recommendations on a simple way to do this? I figure this is an easy one, but I'm new to python so I thought it was worth asking.

Here's my code so far:

db=MySQLdb.connect(...)
cur = db.cursor()
cur.execute("select max(date_val) from my_table;")
min_date = cur.fetchone()[0]

Thanks in advance!

Edit: "print min_date" outputs "None" if the value is null. I want to override it with a default value, such as "2010-01-01".

+1  A: 

Try this:

min_date = cur.fetchone()[0]
min_date = min_date if min_date is not None else default_value
Michał Marczyk
That's what I was looking for. Thanks!
Ike Walker
+3  A: 

I could do this in the MySQL using a sub-query, but would prefer to do it in python.

Why do you say you need a subquery? You can just use COALESCE:

"select COALESCE(max(date_val), 'your_default_value_here') from my_table;"
Mark Byers
You are correct. This is a good way to do it, but I'm glad to know how to do it in python now too. Thanks!
Ike Walker