When I'm trying to format an SQL statement this way:
cursor.execute('SELECT (%s) FROM table WHERE id = 12345', (column,))
it doesn't work properly. Instead of returning values from the specified column, it just returns the name of the column. Any way to fix that?
It only works with formatted string, but according to reviews it is not the safest approach
-
1Object name cannot be a parameter.Akina– Akina2023年01月11日 08:52:15 +00:00Commented Jan 11, 2023 at 8:52
-
Can you add output?Capitan Security– Capitan Security2023年01月11日 09:11:57 +00:00Commented Jan 11, 2023 at 9:11
1 Answer 1
You can't bind column names like that -you're binding a string literal with that name.
If you want to dynamically set the column names, you'll have to resort to string manipulation of some sort, e.g.:
cursor.execute(f'SELECT {column} FROM table WHERE id = 12345')
Of course if column is created by user-input, you'll have to sanitize it somehow.
Comments
Explore related questions
See similar questions with these tags.