Python MySQLdb converters isn't working

 ̄綄美尐妖づ 提交于 2019-12-05 08:54:34

Your conversions dictionary needs to use MySQL types for the keys, not Python types:

import _mysql  
from MySQLdb.constants import FIELD_TYPE
my_conv = { FIELD_TYPE.LONG: int }
db=_mysql.connect(conv=my_con)

From http://mysql-python.sourceforge.net/MySQLdb.html

It appears you need to use _mysql.connect() instead of MySQLdb.connect() in order to use conversions.

I had the same problem but here is the generic solution that you could apply just so that MySQLdb keeps the same data types as sent by mysql. Hope this helps.

try:
    import MySQLdb.converters
except ImportError:
    _connarg('conv')

def connect(host='abc.dev.local', user='abc', passwd='def', db='myabc', port=3306):

    try:
        orig_conv = MySQLdb.converters.conversions
        conv_iter = iter(orig_conv)
        convert = dict(zip(conv_iter, [str,] * len(orig_conv.keys())))
        print "Connecting host=%s user=%s db=%s port=%d" % (host, user, db, port)
        conn = MySQLdb.connect(host, user, passwd, db, port, conv=convert)
    except MySQLdb.Error, e:
        print "Error connecting %d: %s" % (e.args[0], e.args[1])
    return conn
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!