[英]Table name as variable in sql string
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%.
我试过 {} 和 s%。
Thanks谢谢
You can use format function or f-string(if python 3.6=<)您可以使用格式函数或 f-string(如果 python 3.6=<)
tableX = "test"
sql = "SELECT * FROM {} WHERE datum = %s and name = %s".format(tableX)
In Python2.x works first answer:在 Python2.x 中首先回答:
sql = "SELECT * FROM {} WHERE datum = %s and name = %s" .format(tableX)
In Python3 you can use second one with f-string:在 Python3 中,您可以使用带有 f-string 的第二个:
sql = f"SELECT * FROM {tableX} WHERE datum = %s and name = %s"
But, beware of SQL injection.但是,要小心 SQL 注入。 You must be absolutely sure about source of that tableX variable (no user input).
您必须绝对确定该 tableX 变量的来源(无用户输入)。 By direct format of the string you by-pass all escaping of input.
通过直接格式化字符串,您可以绕过所有转义输入。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.