Thursday, July 31, 2008

Automatically convert data type when using MySQLdb

Add following lines:

from MySQLdb.constants import FIELD_TYPE

def DateTime2string(object):
return str(object)

conv_dict = MySQLdb.converters.conversions
conv_dict[FIELD_TYPE.DATETIME] = DateTime2string

conn = MySQLdb.connect (host = 'host',
port = 'port',
user = 'user',
passwd = 'passwd',
db = 'db',
conv = conv_dict
)
Then the cursor will automatically convert all fields of DateTime type in resultset into str for you.
This trick was inspired by this post which unfortunately didn't work for me.