首页 > 代码库 > Python Mysql Select Dict

Python Mysql Select Dict

Python Select Mysql 日期转换字符串 ,转换为字典

 

Python 读取出来的数据格式不是正规Json ,读取出来,直接是字典

 

Python 2.7

import MySQLdbfrom MySQLdb import converters as covconv = cov.conversions.copy()conv[246] = float  # convert decimals to floatsconv[10] = str  # convert dates to stringsconv[11] = str  # convert TimeDelta_or_None to stringsconv[12] = str  # convert DateTime_or_None to strings# conv[15] = str  # convert DateTime_or_None to stringsconv[7] = str  # convert DateTime_or_None to strings# conv[8] = str  # convert DateTime_or_None to stringsconn = MySQLdb.connect(    host=dbhost,    port=3306,    user=root,    passwd=,    db=mysql,    charset=utf8,     conv=conv)cur = conn.cursor(cursorclass = MySQLdb.cursors .DictCursor)cur.execute("select * from proxies_priv")test_data = cur.fetchall()print test_datacur.close()conn.close()

Python 3.+ tornado

#!/usr/bin/env pythonfrom __future__ import print_functionimport pymysqlfrom tornado import ioloop, genfrom tornado_mysql import poolsfrom pymysql import  converters as cov# from MySQLdb import converters as covfrom tornado_mysql.cursors import DictCursorpools.DEBUG = Trueconv = cov.conversions.copy()conv[246] = float  # convert decimals to floatsconv[10] = str  # convert dates to stringsconv[11] = str  # convert TimeDelta_or_None to stringsconv[12] = str  # convert DateTime_or_None to strings# conv[15] = str  # convert DateTime_or_None to stringsconv[7] = str  # convert DateTime_or_None to stringsPOOL = pools.Pool(    dict(host=dbhost, port=3306, user=root, passwd=, db=mysql,    charset=utf8,     conv=conv ,cursorclass=DictCursor)    ,    max_idle_connections=1,    max_recycle_sec=3)@gen.coroutinedef worker(n):    cur = yield POOL.execute("SELECT  * FROM proxies_priv limit 10")    print(cur.fetchall())@gen.coroutinedef main():    workers = [worker(i) for i in range(1)]    yield workersioloop.IOLoop.current().run_sync(main)print(POOL._opened_conns)

 

输出结果

[{User: root, Host: localhost, Proxied_host: ‘‘, With_grant: 1, Proxied_user: ‘‘, Timestamp: 2017-05-04 09:07:49, Grantor: ‘‘}, {User: root, Host: pe-stats.wondershare.cn, Proxied_host: ‘‘, With_grant: 1, Proxied_user: ‘‘, Timestamp: 2017-05-04 09:07:49, Grantor: ‘‘}]

 

Python Mysql Select Dict