Q:

python sqlite3 CREATE TABLE escape using list as headings?

I am trying to use a list as headings in my sqlite3 table using this code:
import sqlite3 as lite

headers = ['Id', 'Name', 'Price']

con = lite.connect('test.sqlite3')

with con:

    cur = con.cursor()
    cur.execute("CREATE TABLE Cars(? INT, ? TEXT, ? INT)", tuple(headers))

However I am getting this error:
OperationalError: near "?": syntax error 

Any ideas on how to get this to work?

A:

In SQL queries from Python, placeholders (such as ?) are only allowed where values would be -- actual data.  For metadata like names of tables and fields, you unfortunately need string substitution.
So in this case
qry = 'CREATE TABLE Cars({} INT, {} TEXT, {} INT)'.format(*headers)
cursor.execute(qry)

Of course, this does expose you to a risk of SQL injection if the headers come from an untrusted source -- no way to safely accept metadata from an untrusted source, you'll have to scrub/verify the query yourself before sending it on.

