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
-
try this: sql = f"SELECT * FROM {tableX} WHERE datum = %s and name = %s"apet– apet2020年02月22日 08:07:16 +00:00Commented Feb 22, 2020 at 8:07
-
Could you elaborate on what database you intend to connect and what connector you will use for that.jlandercy– jlandercy2020年02月22日 08:16:48 +00:00Commented Feb 22, 2020 at 8:16
-
How would you put a variable in any other string?OneCricketeer– OneCricketeer2020年02月22日 08:20:56 +00:00Commented Feb 22, 2020 at 8:20
2 Answers 2
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
DARK_C0D3R
2,27721 silver badges23 bronze badges
Sign up to request clarification or add additional context in comments.
1 Comment
Imhotep
Great with that, why is everything so complicated in Python :)
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
Pavel Francírek
1883 silver badges10 bronze badges
Comments
default