天天看點

【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()