首页 > 数据库技术 > 详细

python mysqldb 返回字典

时间:2020-01-20 16:11:03      阅读:86      评论:0      收藏:0      [点我收藏+]

MySQLdb默认查询结果都是返回tuple,输出时候不是很方便,必须按照0,1这样读取,无意中在网上找到简单的修改方法,就是传递一个cursors.DictCursor就行。

默认程序:

  1.  
    import MySQLdb
  2.  
    db = MySQLdb.connect(host=‘localhost‘, user=‘root‘, passwd=‘123456‘, db=‘test‘)
  3.  
    cur = db.cursor()
  4.  
    cur.execute(‘select * from user‘)
  5.  
    rs = cur.fetchall()
  6.  
    print rs
  7.  
    # 返回类似如下
  8.  
    # ((1000L, 0L), (2000L, 0L), (3000L, 0L))

修改后:

 

  1.  
    import MySQLdb
  2.  
    import MySQLdb.cursors
  3.  
    db = MySQLdb.connect(host=‘localhost‘, user=‘root‘, passwd=‘123456‘, db=‘test‘,
  4.  
    cursorclass=MySQLdb.cursors.DictCursor)
  5.  
    cur = db.cursor()
  6.  
    cur.execute(‘select * from user‘)
  7.  
    rs = cur.fetchall()
  8.  
    print rs
  9.  
    # 返回类似如下
  10.  
    # ({‘age‘: 0L, ‘num‘: 1000L}, {‘age‘: 0L, ‘num‘: 2000L}, {‘age‘: 0L, ‘num‘: 3000L})

 

或者也可以用下面替换connect和cursor部分

 

  1.  
    db = MySQLdb.connect(host=‘localhost‘, user=‘root‘, passwd=‘123456‘, db=‘test‘)
  2.  
    cur = db.cursor(cursorclass=MySQLdb.cursors.DictCursor)
 

python mysqldb 返回字典

原文:https://www.cnblogs.com/chengfengchi/p/12218333.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!