As far as I can tell Sqlite doesn't support INFORMATION_SCHEMA. Instead it has sqlite_master.
I don't think you can get the list you want in just one command. You can get the information you need using sql or pragma, then use regex to split it into the format you need
SELECT sql FROM sqlite_master WHERE name='tablename';
gives you something like
CREATE TABLE tablename(
col1 INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
col2 NVARCHAR(100) NOT NULL,
col3 NVARCHAR(100) NOT NULL,
)
Assuming that you know the table name, and want the names of the data columns you can use the listed code will do it in a simple and elegant way to my taste:
import sqlite3
def get_col_names():
#this works beautifully given that you know the table name
conn = sqlite3.connect("t.db")
c = conn.cursor()
c.execute("select * from tablename")
return [member[0] for member in c.description]
import sqlite3
db = sqlite3.connect('~/foo.sqlite')
dbc = db.cursor()
dbc.execute("PRAGMA table_info('bar')"
ciao = dbc.fetchall()
HeaderList=[]
for i in ciao:
counter=0
for a in i:
counter+=1
if( counter==2):
HeaderList.append(a)
print(HeaderList)
I like the answer by @thebeancounter, but prefer to parameterize the unknowns, the only problem being a vulnerability to exploits on the table name. If you're sure it's okay, then this works:
def get_col_names(cursor, tablename):
"""Get column names of a table, given its name and a cursor
(or connection) to the database.
"""
reader=cursor.execute("SELECT * FROM {}".format(tablename))
return [x[0] for x in reader.description]
If it's a problem, you could add code to sanitize the tablename.
Well, I may be very late to answer this but since people still follow this thread, I just wanted to share how I use to get the list of column names in python sqlite3.
import sqlite3
def getVarList(con, tableName)
return [fields[1] for fields in con.execute(f"PRAGMA table_info({tableName})").fetchall()]
conn = sqlite3.connect('foo.db')
varList = getVarList(conn, 'bar')
import sqlite3
with sqlite3.connect('statics.db') as cur:
cur.execute("CREATE TABLE IF NOT EXISTS data(id INT PRIMARY KEY NOT NULL)")
pragmas = cur.execute("PRAGMA table_info(data);")
columns = [n for _, n, *_ in pragmas.fetchall()]
print(columns)