Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python placing a varible into a sql FROM statement

Tags:

python

sql

Hi am trying to make a sql statement that I able to give the table and a where in python

SQL = "SELECT * FROM (%s) WHERE team_number=(%s) AND match_number=(%s);"
DATA = ('data', 2, 3)
cur.execute(SQL, DATA)
query = cur.fetchall()

The error that I get is psycopg2.ProgrammingError: syntax error at or near "'data'"

and SELECT * FROM ('data') WHERE team_number=(2) and match_number=(3)

Note: I am using (%s) to stop sql injections

like image 491
Victor Henriksson Avatar asked Sep 12 '26 07:09

Victor Henriksson


1 Answers

Most prepared statements APIs, including Python's, do not allow the table or column names to be parameters. Instead, you would have to hard code the table name:

SQL = "SELECT * FROM data WHERE team_number=(%s) AND match_number=(%s);"
DATA = (2, 3)
cur.execute(SQL, DATA)
query = cur.fetchall()

The reason is that allowing the table name to be a parameter might expose you to a security risk. Imagine if someone were to hack your UI drop down and then choose the user table. Then, they might get access to data they should not be seeing.

like image 86
Tim Biegeleisen Avatar answered Sep 13 '26 19:09

Tim Biegeleisen