How to retrieve SQL result column value using column name in Python?

后端 未结 10 1121
闹比i
闹比i 2020-11-27 14:05

Is there a way to retrieve SQL result column value using column name instead of column index in Python? I\'m using Python 3 with mySQL. The syntax I\'m looking for is pretty

10条回答
  •  长情又很酷
    2020-11-27 14:56

    The MySQLdb module has a DictCursor:

    Use it like this (taken from Writing MySQL Scripts with Python DB-API):

    cursor = conn.cursor(MySQLdb.cursors.DictCursor)
    cursor.execute("SELECT name, category FROM animal")
    result_set = cursor.fetchall()
    for row in result_set:
        print "%s, %s" % (row["name"], row["category"])
    

    edit: According to user1305650 this works for pymysql as well.

提交回复
热议问题