1

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

Mureinik
316k54 gold badges403 silver badges406 bronze badges
asked Jan 11, 2023 at 8:43
2
  • 1
    Object name cannot be a parameter. Commented Jan 11, 2023 at 8:52
  • Can you add output? Commented Jan 11, 2023 at 9:11

1 Answer 1

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.

answered Jan 11, 2023 at 9:07
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.