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

后端 未结 10 1025
闹比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.

    0 讨论(0)
  • 2020-11-27 14:56
    import mysql.connector as mysql
    ...
    cursor = mysql.cnx.cursor()
    cursor.execute('select max(id) max_id from ids')
    (id) = [ id for id in cursor ]
    
    0 讨论(0)
  • 2020-11-27 15:00

    you must look for something called " dictionary in cursor "

    i'm using mysql connector and i have to add this parameter to my cursor , so i can use my columns names instead of index's

    db = mysql.connector.connect(
        host=db_info['mysql_host'],
        user=db_info['mysql_user'],
        passwd=db_info['mysql_password'],
        database=db_info['mysql_db'])
    
    cur = db.cursor()
    
    cur = db.cursor( buffered=True , dictionary=True)
    
    0 讨论(0)
  • 2020-11-27 15:04

    python 2.7

    import pymysql
    
    conn = pymysql.connect(host='localhost', port=3306, user='root', passwd='password', db='sakila')
    
    cur = conn.cursor()
    
    n = cur.execute('select * from actor')
    c = cur.fetchall()
    
    for i in c:
        print i[1]
    
    0 讨论(0)
提交回复
热议问题