2

Simple SQL statement:

sql = "DROP TABLE IF EXISTS %s"
cursor.execute(sql, ("user_table",))

It fails with:

psycopg2.ProgrammingError: syntax error at or near "'user_table'"
LINE 1: DROP TABLE IF EXISTS 'user_table'

The single quotes in the SQL statement are the problem. If I run this it works just fine:

cursor.execute("DROP TABLE IF EXISTS user_table")

2 Answers 2

5

The AsIs adapter is useful for objects whose string representation is already valid as SQL representation

from psycopg2.extensions import AsIs

sql = "DROP TABLE IF EXISTS %s"
cursor.execute(sql, (AsIs("user_table"),))
Sign up to request clarification or add additional context in comments.

Comments

3

You can use the argument-syntax only for arguments, not for table or column names.

2 Comments

And that makes total sense. Thanks!
More strictly, query parameters are suitable for passing literals only. You cannot use them to substitute identifiers or keywords.

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.