PepperoniPizza
PepperoniPizza

Reputation: 9112

Django raw sql format tablename

I am trying to interpolate the tablename into a raw sql but it's interpolating a badly formatted string so the SQL query fails. I can't find a proper way of interpolating the string into the SQL query properyly:

from django.db import connection
cursor = connection.cursor()
cursor.execute("SELECT * from %s;", ['product'])

Throws:

django.db.utils.ProgrammingError: syntax error at or near "'product'"
LINE 1: SELECT * from 'product';

Upvotes: 3

Views: 2749

Answers (1)

mechanical_meat
mechanical_meat

Reputation: 169444

You can't pass table nor column names as parameter arguments. Instead do something like:

qry = "SELECT * from %s;" % 'product'
cursor.execute(qry)

While being mindful of the possibility of SQL-injection attack.

Upvotes: 6

Related Questions