I am working on a Python web project using a postgres
database as backend with the psycopg2
package.
Earlier, I was trying static
query for truncate
command for demo purpose, after it works, I tried to make it dynamic
, thereby passing table name
.
def clear_tables(query: str, vars_list: list[Any]):
# psycog 2 connection engine code
cursor.executemany(query=query, vars_list=vars_list)
conn.commit()
def foo():
vars_list: list[Any] = list()
table_name: str = "person"
record: tuple[Any] = (table_name,)
vars_list.append(record)
query = """
TRUNCATE TABLE %s RESTART IDENTITY;
"""
clear_tables(query=query, vars_list=vars_list)
On executing I am getting an error. Somehow the table name
gets unwanted '
single quotes
psycopg2.errors.SyntaxError: syntax error at or near "'person'"
LINE 2: TRUNCATE TABLE 'person' RESTART IDENTITY;
How to remove those quotes?
2
Answers
Make the following changes and retry:
Aside from prevent a whole host of safety issues, this style of formatting prevents SQL Injection attacks. Going forward, it’s better to adopt this style or some of the other possible ones using built in
.format()
.For further reading please check documentation.
This works, and is safe against SQL injection: