How to get field names from SQL database to list in python

Here is the code that I still have:

from ConfigParser import *
import MySQLdb

configuration = ConfigParser()
configuration.read('someconfigfile.conf')
    db = MySQLdb.connect(
    host = configuration.get('DATABASE', 'MYSQL_HOST'),
    user = configuration.get('DATABASE', 'MYSQL_USER'),
    passwd = configuration.get('DATABASE', 'MYSQL_PASS'),
    db = configuration.get('DATABASE', 'MYSQL_DB'),
    port = configuration.getint('DATABASE', 'MYSQL_PORT'),
    ssl = {
        'ca':   configuration.get('SSL_SETTINGS', 'SSL_CA'),
        'cert': configuration.get('SSL_SETTINGS', 'SSL_CERT'),
        'key':  configuration.get('SSL_SETTINGS', 'SSL_KEY')
            },
    )
cursor = db.cursor()
sql = "SELECT column_name FROM information_schema.columns WHERE table_name='met';"
cursor.execute(sql)
list = cursor.fetchall()

print list

here is what prints:

(('field',), ('field',), ('field',), ('field',), ('field',), ('field',), ('field',), ('field',), ('field',), ('field',), ('field',), ('field',), ('field',), ('field',), ('pk_wind_spd2',), ('field',))

And I get a tuple instead of a list. I would rather have a list of strings

+3
source share
1 answer

Not shadow embedded (list), change to

alist = cursor.fetchall()

This generator expression will give you the column names in the tuple:

tuple(i[0] for i in alist)

+2
source

Source: https://habr.com/ru/post/1752317/


All Articles