Richard
Richard

Reputation: 15882

How to get Field names from a SQL database into a list in python

Here is a the code I have so far:

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

this is what prints:

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

And I am getting a tuple instead of a list. I would prefer to have a list of strings

Upvotes: 3

Views: 3500

Answers (1)

mechanical_meat
mechanical_meat

Reputation: 169434

Don't shadow built-ins (list), change to

alist = cursor.fetchall()

This generator expression will get you the column names in a tuple:

tuple(i[0] for i in alist)

Upvotes: 2

Related Questions