简体   繁体   中英

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?

In SQL queries from Python, placeholders (such as ? ) are only allowed where values would be -- actual data. For meta data 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 meta data from an untrusted source, you'll have to scrub/verify the query yourself before sending it on.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM