MySQL: Get column name or alias from query

后端 未结 10 1724
死守一世寂寞
死守一世寂寞 2020-11-28 20:04

I\'m not asking for the SHOW COLUMNS command.

I want to create an application that works similarly to heidisql, where you can specify an SQL query and w

相关标签:
10条回答
  • 2020-11-28 20:23

    Looks like MySQLdb doesn't actually provide a translation for that API call. The relevant C API call is mysql_fetch_fields, and there is no MySQLdb translation for that

    0 讨论(0)
  • 2020-11-28 20:24

    You could also use MySQLdb.cursors.DictCursor. This turns your result set into a python list of python dictionaries, although it uses a special cursor, thus technically less portable than the accepted answer. Not sure about speed. Here's the edited original code that uses this.

    #!/usr/bin/python -u
    
    import MySQLdb
    import MySQLdb.cursors
    
    #===================================================================
    # connect to mysql
    #===================================================================
    
    try:
        db = MySQLdb.connect(host='myhost', user='myuser', passwd='mypass', db='mydb', cursorclass=MySQLdb.cursors.DictCursor)
    except MySQLdb.Error, e:
        print 'Error %d: %s' % (e.args[0], e.args[1])
        sys.exit(1)
    
    #===================================================================
    # query select from table
    #===================================================================
    
    cursor = db.cursor()
    
    sql = 'SELECT ext, SUM(size) AS totalsize, COUNT(*) AS filecount FROM fileindex GROUP BY ext ORDER BY totalsize DESC;'
    
    cursor.execute(sql)
    all_rows = cursor.fetchall()
    
    print len(all_rows) # How many rows are returned.
    for row in all_rows: # While loops always make me shudder!
        print '%s %s %s\n' % (row['ext'], row['totalsize'], row['filecount'])
    
    cursor.close()
    db.close()  
    

    Standard dictionary functions apply, for example, len(row[0]) to count the number of columns for the first row, list(row[0]) for a list of column names (for the first row), etc. Hope this helps!

    0 讨论(0)
  • 2020-11-28 20:29

    Something similar to the proposed solutions, only the result is json with column_header : vaule for db_query ie sql.

    cur = conn.cursor()
    cur.execute(sql)
    res = [dict((cur.description[i][0], value) for i, value in enumerate(row)) for row in cur.fetchall()]
    

    output json example:

    [
       {
          "FIRST_ROW":"Test 11",
          "SECOND_ROW":"Test 12",
          "THIRD_ROW":"Test 13"
       },
       {
          "FIRST_ROW":"Test 21",
          "SECOND_ROW":"Test 22",
          "THIRD_ROW":"Test 23"
       }
    ]
    
    0 讨论(0)
  • 2020-11-28 20:30

    This is only an add-on to the accepted answer:

    def get_results(db_cursor):
        desc = [d[0] for d in db_cursor.description]
        results = [dotdict(dict(zip(desc, res))) for res in db_cursor.fetchall()]
        return results
    

    where dotdict is:

    class dotdict(dict):
        __getattr__ = dict.get
        __setattr__ = dict.__setitem__
        __delattr__ = dict.__delitem__
    

    This will allow you to access much easier the values by column names.
    Suppose you have a user table with columns name and email:

    cursor.execute('select * from users')
    results = get_results(cursor)
    for res in results:
      print(res.name, res.email)
    
    0 讨论(0)
  • 2020-11-28 20:32

    I think this should do what you need (builds on the answer above) . I am sure theres a more pythony way to write it, but you should get the general idea.

    cursor.execute(query)
    columns = cursor.description
    result = []
    for value in cursor.fetchall():
        tmp = {}
        for (index,column) in enumerate(value):
            tmp[columns[index][0]] = column
        result.append(tmp)
    pprint.pprint(result)
    
    0 讨论(0)
  • 2020-11-28 20:32

    Try:

    cursor.column_names
    

    mysql connector version:

    mysql.connector.__version__
    '2.2.9'
    
    0 讨论(0)
提交回复
热议问题