解决torndb(目前对MySQLdb最好的封装)在python3.x下不能用的问题

来源:互联网 发布:日照光华网络教育 编辑:程序博客网 时间:2024/06/05 05:19

        我用的是python3.3,连接MySQL最常用的是MySQLdb,但官方是针对python2.x的,但是我找到一个支持python3.x的版本https://github.com/davispuh/MySQL-for-Python-3 。在python3.3下使用正常,非常给力。但是在tornado中使用的是torndb,这个是对MySQLdb的封装,但使用起来非常方便,而且现在tornado3.0.1 把torndb.py单独分出来,这样我们在其他项目中也能直接用torndb,非常人性化。但是,现在版本的torndb.py直接用在python3上会出错的,下面是我对torndb.py的一些改动:

        在torndb.py 71行,如下:

        args = dict(conv=CONVERSIONS, use_unicode=True, charset="utf8",                    db=database, init_command=('SET time_zone = "%s"' % time_zone),                    connect_timeout=connect_timeout, sql_mode="TRADITIONAL")

use_unicode是python2.x才有的,新的python3.x默认都是utf8,所以把use_unicode=True去掉(大胆跟我做,没事儿的哈)。

        然后在torndb.py query函数中,如下:

 def query(self, query, *parameters, **kwparameters):        """Returns a row list for the given query and parameters."""        cursor = self._cursor()        try:            self._execute(cursor, query, parameters, kwparameters)            column_names = [d[0] for d in cursor.description]            return [Row(itertools.izip(column_names, row)) for row in cursor]        finally:            cursor.close()

izip函数也是python2.x中才有的,作用是把两个list各个元素对应合到一个元组里,并形成一个新的list,在python3.x中用zip_longest代替,换掉就行了。


        好了,修改完毕,这样python3.x就可以正常使用torndb了,是不是非常爽~哈哈 


转载请注明:转自 http://blog.csdn.net/littlethunder/article/details/8917378


原创粉丝点击