I want to get a list of column names from a table in a database. Using pragma I get a list of tuples with a lot of unneeded information. Is there a way to get only the column names? So I might end up with something like this:
[Column1, Column2, Column3, Column4]
The reason why I absolutely need this list is because I want to search for a column name in the list and get the index because the index is used in a lot of my code.
Is there a way of getting a list like this?
Thanks
You can use sqlite3 and pep-249
import sqlite3
connection = sqlite3.connect('~/foo.sqlite')
cursor = connection.execute('select * from bar')
cursor.description is a sequence of 7-item sequences whose first element is the column name:
names = list(map(lambda x: x[0], cursor.description))
Alternatively you could use a list comprehension:
names = [description[0] for description in cursor.description]