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

后端 未结 10 1132
闹比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:42

    import pymysql

    # Open database connection
    db = pymysql.connect("localhost","root","","gkdemo1")
    
    # prepare a cursor object using cursor() method
    cursor = db.cursor()
    
    # execute SQL query using execute() method.
    cursor.execute("SELECT * from user")
    
    # Get the fields name (only once!)
    field_name = [field[0] for field in cursor.description]
    
    # Fetch a single row using fetchone() method.
    values = cursor.fetchone()
    
    # create the row dictionary to be able to call row['login']
    **row = dict(zip(field_name, values))**
    
    # print the dictionary
    print(row)
    
    # print specific field
    print(**row['login']**)
    
    # print all field
    for key in row:
        print(**key," = ",row[key]**)
    
    # close database connection
    db.close()
    

提交回复
热议问题