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

后端 未结 10 1024
闹比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()
    
    0 讨论(0)
  • 2020-11-27 14:47

    This post is old but may come up via searching.

    Now you can use mysql.connector to retrive a dictionary as shown here: https://dev.mysql.com/doc/connector-python/en/connector-python-api-mysqlcursordict.html

    Here is the example on the mysql site:

    cnx = mysql.connector.connect(database='world')
    cursor = cnx.cursor(dictionary=True)
    cursor.execute("SELECT * FROM country WHERE Continent = 'Europe'")
    
    print("Countries in Europe:")
    for row in cursor:
        print("* {Name}".format(Name=row['Name']))
    
    0 讨论(0)
  • 2020-11-27 14:51

    Of course there is. In Python 2.7.2+...

    import MySQLdb as mdb
    con =  mdb.connect('localhost', 'user', 'password', 'db');
    cur = con.cursor()
    cur.execute('SELECT Foo, Bar FROM Table')
    for i in range(int(cur.numrows)):
        foo, bar = cur.fetchone()
        print 'foo = %s' % foo
        print 'bar = %s' % bar
    
    0 讨论(0)
  • 2020-11-27 14:52

    selecting values from particular column:

    import pymysql
    db = pymysql.connect("localhost","root","root","school")
    cursor=db.cursor()
    sql="""select Total from student"""
    l=[]
    try:
        #query execution
        cursor.execute(sql)
        #fetch all rows 
        rs = cursor.fetchall()
        #iterate through rows
        for i in rs:
            #converting set to list
            k=list(i)
            #taking the first element from the list and append it to the list
            l.append(k[0])
        db.commit()
    except:
        db.rollback()
    db.close()
    print(l)
    
    0 讨论(0)
  • 2020-11-27 14:52

    You didn't provide many details, but you could try something like this:

    # conn is an ODBC connection to the DB
    dbCursor = conn.cursor()
    sql = ('select field1, field2 from table') 
    dbCursor = conn.cursor()
    dbCursor.execute(sql)
    for row in dbCursor:
        # Now you should be able to access the fields as properties of "row"
        myVar1 = row.field1
        myVar2 = row.field2
    conn.close()
    
    0 讨论(0)
  • 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
    
    0 讨论(0)
提交回复
热议问题