MySQL: Get column name or alias from query

后端 未结 10 1763
死守一世寂寞
死守一世寂寞 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条回答
  •  萌比男神i
    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)
    

提交回复
热议问题