Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to get a list of column names in sqlite?

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

like image 719
Denman Avatar asked Oct 20 '11 05:10

Denman


People also ask

How do I see all columns in SQLite?

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 + ].

How do I get a list of all columns?

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'


2 Answers

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] 
like image 152
smallredstone Avatar answered Sep 30 '22 07:09

smallredstone


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.

like image 44
flokk Avatar answered Sep 30 '22 08:09

flokk