天天看点

【Python】转换mysql 结果集为词典类型

python的mysqldb模块是python连接mysql的一个模块,

使用mysqldb 模块获取mysql中的记录,默认查询结果返回是tuple类型,只能通过0,1等索引下标访问数据。

<b>默认的连接方式:</b>

conn = mysqldb.connect(host=dbconn.db_host,port=int(dbconn.db_port),user=dbconn.db_user,passwd=dbconn.db_pass, charset='utf8')

root@alsdb_admin1b # python dict.py 

the type of res1 is :  

(u'com_delete', u'6491620')

----------------------------------------

使用 

import mysqldb.cursors

在conn 中加上 cursorclass = mysqldb.cursors.dictcursor

conn = mysqldb.connect(host=dbconn.db_host,port=int(dbconn.db_port),user=dbconn.db_user,passwd=dbconn.db_pass, charset='utf8',cursorclass = mysqldb.cursors.dictcursor)

<b>返回的结果集仍然是 tuple 类型但是 结果机里面的值已经变为词典类型了,但是这样并不能解决问题</b>

the type of res2 is :  <b></b>

{'value': u'6491620', 'variable_name': u'com_delete'}

使用<b>dict(result) </b>将结果集转换为词典,得到如下结果:

the type of mystat2 is :  

{u'com_delete': u'6491620'}

这样可以直接使用mystat2['com_delete'] 来调用对应的vlaue

dict.py的代码:

#!/usr/bin/env python

#coding=utf-8

import time

import sys

import mysqldb

import dbconn

def now() :

        #return str('2011-01-31 00:00:00')

        return str( time.strftime( '%y-%m-%d %h:%m:%s' , time.localtime() ) )

def log( qps,tps , logs ) :

        f = file( logs , 'a' , 0 )

        f.write( now() + '  ' + str(qps) +'  '+ str(tps) + '\n' )

        f.close()

def main() :

    try: 

      conn = mysqldb.connect(host=dbconn.db_host,port=int(dbconn.db_port),user=dbconn.db_user,passwd=dbconn.db_pass, charset='utf8')

    except  mysqldb.error,e:

      print "error %d:%s"%(e.args[0],e.args[1])

      exit(1)

    conn.autocommit(true)

    cursor=conn.cursor()

    mystat1={}

    sql = "show global status where variable_name in ('com_delete');"

    cursor.execute(sql)

    res1 = cursor.fetchall()

    for row in res1: 

        print "the type of res1 is : ", type(row)

        print row

    conn.close()

    print "----------------------------------------\n" 

    try:

      conn = mysqldb.connect(host=dbconn.db_host,port=int(dbconn.db_port),user=dbconn.db_user,passwd=dbconn.db_pass, charset='utf8',cursorclass = mysqldb.cursors.dictcursor)

    mystat2={}

    res2 = cursor.fetchall()

    #mystat2=dict(res2)

    for row in res2:

        print "the type of res2 is : ", type(res2)

        print row  

    print "----------------------------------------\n"

    mystat2=dict(res2)

    print "the type of mystat2 is : ", type(mystat2)

    print mystat2

if __name__ == '__main__':

   main()