【Python】轉換mysql 結果集為詞典型別

楊奇龍發表於2013-07-27
Python的MySQLdb模組是Python連線MySQL的一個模組,
使用MySQLdb 模組獲取mysql中的記錄,預設查詢結果返回是tuple型別,只能透過0,1等索引下標訪問資料。
預設的連線方式:
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)
返回的結果集仍然是 tuple 型別但是 結果機裡面的值已經變為詞典型別了,但是這樣並不能解決問題
the type of res2 is :  
{'Value': u'6491620', 'Variable_name': u'Com_delete'}
----------------------------------------
使用dict(result) 將結果集轉換為詞典,得到如下結果:
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
import MySQLdb.cursors
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)
    except  MySQLdb.ERROR,e:
      print "Error %d:%s"%(e.args[0],e.args[1])
      exit(1)

    conn.autocommit(True)
    cursor=conn.cursor()
    mystat2={}
    cursor.execute(sql)
    res2 = cursor.fetchall()
    #mystat2=dict(res2)
    for row in res2:
        print "the type of res2 is : ", type(res2)
        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')
    except  MySQLdb.ERROR,e:
      print "Error %d:%s"%(e.args[0],e.args[1])
      exit(1)
    conn.autocommit(True)
    cursor=conn.cursor()
    mystat2={}
    cursor.execute(sql)
    res2 = cursor.fetchall()
    mystat2=dict(res2)
    print "the type of mystat2 is : ", type(mystat2)
    print mystat2
    conn.close()
if __name__ == '__main__':
   main()

來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/22664653/viewspace-767271/,如需轉載,請註明出處,否則將追究法律責任。

相關文章