1

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
7
  • what SQL query do you expect to get ? where do you have column names and columns types. I'm not sure but ? expects only one element but you have many elements. Commented Oct 18, 2016 at 22:50
  • I don't query yet, tried to add types and it didn't help. The size of the list may change, that's why I can't determine an exact number of question marks. Commented Oct 18, 2016 at 22:52
  • maybe first generate one string with column names and column types and then use it as single argument in query. Commented Oct 18, 2016 at 22:55
  • Is there any smart way to do so besides creating a loop that concatenates the question marks string (?,?,?,?,?...) with the argument parts altogether? Commented Oct 18, 2016 at 23:02
  • 1
    You cannot pass structural components like column names as parameters only data values usually in WHERE, ON, VALUES(), and IN() clauses. You will need to concatenate list values to SQL string. Commented Oct 19, 2016 at 0:05

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.