python的mysqldb返回的结果集为字典类型

from http://blog.csdn.net/suofiya2008/article/details/5690506

默认mysqldb返的是元组,这样对使用者不太友好,也不利于维护
下面是解决方法

  1. import MySQLdb
  2. import   MySQLdb . cursors
  3.  
  4. conn MySQLdb . Connect (
  5.     host = ' localhost ' user = ' root ' ,
  6.     passwd = '' db = ' test ' , compress = 1 ,
  7.     cursorclass = MySQLdb . cursors . DictCursor )   # <- important
  8. cursor conn . cursor ()
  9. cursor . execute ( " SELECT name, sometext txt FROM foo " )
  10. rows cursor . fetchall ()
  11. cursor . close ()
  12. conn . close ()
  13.  
  14. for   row in rows :
  15.     print   row [ ' name ' ] row [ ' txt ' ] # bingo!
  16.  
  17. # another (even better) way is:
  18.  
  19. conn MySQLdb . Connect (
  20.     host = ' localhost ' user = ' root ' ,
  21.     passwd = '' db = ' test ' , compress = 1 )
  22. cursor conn . cursor ( cursorclass = MySQLdb . cursors . DictCursor )
  23. # ...
  24. # results by field name
  25. cursor conn . cursor ()
  26. # ...
  27. # ...results by field number
请使用浏览器的分享功能分享到微信等