开发者

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

开发者 https://www.devze.com 2023-01-05 07:39 出处:网络
Here is a the code I have so far: from ConfigParser import * import MySQLdb configuration = ConfigParser()

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 stri开发者_C百科ngs


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)

0

精彩评论

暂无评论...
验证码 换一张
取 消