1

From Python's documentation (https://docs.python.org/3/library/sqlite3.html#sqlite3.Cursor.execute), I should be able to execute SQL statements using parameterized placeholders. Yet, the code below doesn't work.

import sqlite3

conn = sqlite3.connect("temp.db")
c = conn.cursor()

c.execute("create table ? (foo text, bar text)", ("table_name",))

conn.commit()
conn.close()

I'm getting an error:

Traceback (most recent call last):
  File "main.py", line 6, in <module>
    c.execute("create table ? (foo text, bar text)", ("table_name",))
sqlite3.OperationalError: near "?": syntax error

But if I switch out of using parameterized placeholders, it works.

1 Answer 1

1

In a word - no. You can only parameterize values, not object names (in this case, the table's name). If you want to do something like this, you'd have to resort to string manipulation, e.g.:

c.execute("create table %s (foo text, bar text)" % ("table_name"))
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! I'm just learning SQL so I never realized the distinction between values and objects.

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.