原文链接:http://zetcode.com/databases/mysqlpythontutorial/
翻译作者:kodango dangoakachan at foxmail dot com
译文链接:
a. https://kodango.com/mysql-python-tutorial-part-one
b. https://kodango.com/mysql-python-tutorial-part-two
译者注:本文的前半部分请看上一篇文章。
字典游标
在 MySQLdb 模块中有许多种游标类型。默认的游标类型以元组的元组形式返回数据。当我们使用字典游标时,这些数据是以Python字典的形式返回。这样一来,我们就可以通过列名来访问数据。
#!/usr/bin/python # -*- coding: utf-8 -*- import MySQLdb as mdb import sys con = mdb.connect('localhost', 'testuser', 'test623', 'testdb') with con: cur = con.cursor(mdb.cursors.DictCursor) cur.execute("SELECT * FROM Writers") rows = cur.fetchall() for row in rows: print "%s %s" % (row["Id"], row["Name"])