0

can someone tell me how to make the table a variable?

tableX = "test"
sql = "SELECT * FROM tableX WHERE datum = %s and name = %s" 
val = (datumX, nameX,)

I just can't get it right. I've tried {}and also s%.

Thanks

OneCricketeer
193k20 gold badges147 silver badges277 bronze badges
asked Feb 22, 2020 at 8:02
3
  • try this: sql = f"SELECT * FROM {tableX} WHERE datum = %s and name = %s" Commented Feb 22, 2020 at 8:07
  • Could you elaborate on what database you intend to connect and what connector you will use for that. Commented Feb 22, 2020 at 8:16
  • How would you put a variable in any other string? Commented Feb 22, 2020 at 8:20

2 Answers 2

1

You can use format function or f-string(if python 3.6=<)

tableX = "test"
sql = "SELECT * FROM {} WHERE datum = %s and name = %s".format(tableX)
answered Feb 22, 2020 at 8:12
Sign up to request clarification or add additional context in comments.

1 Comment

Great with that, why is everything so complicated in Python :)
1

In Python2.x works first answer:

sql = "SELECT * FROM {} WHERE datum = %s and name = %s" .format(tableX)

In Python3 you can use second one with f-string:

sql = f"SELECT * FROM {tableX} WHERE datum = %s and name = %s"

But, beware of SQL injection. You must be absolutely sure about source of that tableX variable (no user input). By direct format of the string you by-pass all escaping of input.

answered Feb 22, 2020 at 8:21

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.