MySQLdb fetchall返回字典的方法

MySQLdb  默认查询返回的是元祖

def book_list(request):
db = MySQLdb.connect(user=’root’,db=’cms’,passwd=’123456′,host=’localhost’,charset=”utf8″)

#返回字典方式

cursor = db.cursor(MySQLdb.cursors.DictCursor)   //设置参数
cursor.execute(“select * from article”);
articles = cursor.fetchall()
db.close()
return render(request,’books.html’,{‘articles’:articles})

 

 

{% for x in articles %}
{{ x.id }}|{{ x.title }}|{{ x.content }}<br/>
{% endfor %}

 

 

def book_list1(request):
db = MySQLdb.connect(user=’root’,db=’cms’,passwd=’123456′,host=’localhost’,charset=”utf8″)

#默认返回元祖方式

cursor = db.cursor()
cursor.execute(“select * from article”);
articles = cursor.fetchall()
db.close()
return render(request,’books.html’,{‘articles’:articles})

 

{% for x in articles %}
{{ x.0 }}|{{ x.1 }}|{{ x.2 }}<br/>

{% endfor %}

 


设置参数即可


https://stackoverflow.com/questions/12867140/python-mysqldb-get-the-result-of-fetchall-in-a-list
  cur = db.cursor(MySQLdb.cursors.DictCursor)


I'm sure that after all this time, you've solved this problem, however, for some people who may not know how to get the values of a cursor as a dictionary using MySQLdb, you can use this method found here:

import MySQLdb as mdb

con = mdb.connect('localhost', 'testuser', 'test623', 'testdb')

with con:

    cur = con.cursor(mdb.cursors.DictCursor)
    cur.execute("SELECT * FROM Writers LIMIT 4")

    rows = cur.fetchall()

    for row in rows:
        print row["Id"], row["Name"]

更多内容请关注我的订阅号:

个人博客 : http://www.zxb8.cc/ 自学吧

转载于:https://my.oschina.net/yonghan/blog/1921689

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值