2

So, I am new to Stackoverflow and I hope I'm writing this question well. So I'm trying to choose a table from my database (that contains 5 tables) based on user input in python. However I'm not quite sure how to do it. Here is the code:

user_input = "table1"
db.execute("SELECT number FROM (?) WHERE person = 1;")

I'm searching for a way if it is possible. Anyway any help would be appreciated.

  • Unfortunately no :( –  Jul 19 '20 at 19:35
  • As noted in the duplicate, it is not possible to pass the tablename as a parameter, so your only option is query building (like in the answer you got), but *do not forget* to sanitize / whitelist the input. – Ilja Everilä Jul 31 '20 at 18:08

1 Answers1

0

Well, after some verifications in order to forbid SQL injections, the easiest way is to format the query string with the user input.

db.execute ("SELECT * FROM MyTable WHERE person = {};".format(user_input))

And the content of user_input would be placed on the curly brackets.

It's not very clear on how you're getting user input, though.

Gabriel Milan
  • 702
  • 2
  • 7
  • 21
  • My question was about choosing the table not the person and btw I've just created this user_input for simplicity.(Instead of MyTable I want the user_input) –  Jul 19 '20 at 19:31
  • It's the same idea, you just need to replace it with curly brackets: `db.execute ("SELECT number FROM {} WHERE person = 1;".format(user_input))` – Gabriel Milan Jul 19 '20 at 19:34
  • 1
    Thanks, I wish I can upvote your question. Anyway Thanks –  Jul 19 '20 at 19:40