I have the need to convert NULLs returned from the database to a float(0) instead of a None. I have my reasons for doing this.
Apparently all you have to do is make a copy of MySQLdb.converters.conversions and modify it to meet you needs. So I wrote the following function:
def NULL2Zero :
return float(0)
Then I copied the coversions dictionary like so:
from MySQLdb.converters import conversions
from MySQLdb.constants import FIELD_TYPE
myconv = conversions.copy()
myconv[FIELD_TYPE.NULL] = NULL2Zero
Then I connect to the database with the conv parameter of the connect method set to myconv.
But, it doesn't seem to do anything. The NULLs are still getting returned as None.
Anyone else done this? What am I doing wrong?
If you would like to refer to this comment somewhere else in this project, copy and paste the following link:
I have the need to convert NULLs returned from the database to a float(0) instead of a None. I have my reasons for doing this.
Apparently all you have to do is make a copy of MySQLdb.converters.conversions and modify it to meet you needs. So I wrote the following function:
def NULL2Zero :
return float(0)
Then I copied the coversions dictionary like so:
from MySQLdb.converters import conversions
from MySQLdb.constants import FIELD_TYPE
myconv = conversions.copy()
myconv[FIELD_TYPE.NULL] = NULL2Zero
Then I connect to the database with the conv parameter of the connect method set to myconv.
But, it doesn't seem to do anything. The NULLs are still getting returned as None.
Anyone else done this? What am I doing wrong?
I don't know about the connect usage, but have you tried casting things in MySQL?
Doing something like:
SELECT CAST(MyPotentiallyNullField AS FLOAT) ....
Should do the trick.. I don't know if they accept float, but maybe LONG, or DOUBLE, or whatever... IT worked for me with INT's and NULLS.
Keep in mind this functionality only works in MySQL 4.1 and above, I think. Still, super handy. :)