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
Show all columns in a SQLite table. In TablePlus, you can either open the Query Editor and run the statements above, or see all columns from the GUI's table structure view: From the table data view, to switch to structure view, click on the Structure button at the bottom of the window, or press Command + Control + ].
To get the column name of a table we use sp_help with the name of the object or table name. sp_columns returns all the column names of the object. The following query will return the table's column names: sp_columns @table_name = 'News'
You can use sqlite3 and pep-249
import sqlite3 connection = sqlite3.connect('~/foo.sqlite') cursor = connection.execute('select * from bar')
cursor.description is description of columns
names = list(map(lambda x: x[0], cursor.description))
Alternatively you could use a list comprehension:
names = [description[0] for description in cursor.description]
An alternative to the cursor.description solution from smallredstone could be to use row.keys():
import sqlite3 connection = sqlite3.connect('~/foo.sqlite') connection.row_factory = sqlite3.Row cursor = connection.execute('select * from bar') # instead of cursor.description: row = cursor.fetchone() names = row.keys()
The drawback: it only works if there is at least a row returned from the query.
The benefit: you can access the columns by their name (row['your_column_name'])
Read more about the Row objects in the python documentation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With