Search code examples
pythonpython-3.xsqlitepragma

Parsing the output of sqlite PRAGMA information into a python list


I am trying to use the SQLite command to gather information on column names:

columnsQuery = ("PRAGMA table_info(%s)" % (table))
columnNames = cursor.execute(columnsQuery)

Per the research i've done, executing this command should give me the column names within a given table. Because of the fact that I do not have a sqlite database readily available, I am unaware of what the output of PRAGMA looks like. Is there a way that I can parse my variable "columnNames" to be a Python list of column names?


Solution

  • The output of a pragma has columns and rows, just like a query:

    $ sqlite3
    SQLite version 3.18.0 2017-02-11 14:59:58
    Enter ".help" for usage hints.
    Connected to a transient in-memory database.
    Use ".open FILENAME" to reopen on a persistent database.
    sqlite> create table t(id integer primary key, name text not null, date default current_date);
    sqlite> .mode columns
    sqlite> .header on 
    sqlite> pragma table_info(t);            
    cid         name        type        notnull     dflt_value  pk        
    ----------  ----------  ----------  ----------  ----------  ----------
    0           id          integer     0                       1         
    1           name        text        1                       0         
    2           date                    0           current_da  0