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

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

    import mysql
    import mysql.connector
    
    db = mysql.connector.connect(
       host = "localhost",
        user = "root",
        passwd = "P@ssword1",
        database = "appbase"
    )
    
    cursor = db.cursor(dictionary=True)
    
    sql = "select Id, Email from appuser limit 0,1"
    cursor.execute(sql)
    result = cursor.fetchone()
    
    print(result)
    # output =>  {'Id': 1, 'Email': 'me@gmail.com'}
    
    print(result["Id"])
    # output => 1
    
    print(result["Email"])
    # output => me@gmail.com
    

提交回复
热议问题