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://*.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