简体   繁体   中英

How to create sqlite3 table columns from a list? (in python)

I'm trying to build a table columns according to a user request (the size of the list may change, that's why I can't determine an exact number of question marks):

userInput=[a,b,c,d,e,f,g]
ct.execute('CREATE TABLE IF NOT EXISTS chars(?)',(userInput))

I get the following error:

sqlite3.OperationalError: near "?": syntax error

To answer your question, we will ignore security issues. I assume you want to create (untyped) columns according to your python list.

CREATE TABLE chars (a,b,c,d,e,f,g)

Here is my proposal:

userInput=['a','b','c','d','e','f','g']
q = "CREATE TABLE IF NOT EXISTS chars(%s)" % ", ".join(userInput)

(Note that the column names must be quoted, per the Python syntax of string literals).

It may be argued that %s as a syntax is "de-emphasized", but in my humble opinion it is nicely terse in that case.

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