Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/284.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python psycopg2传入表名_Python_Psycopg2 - Fatal编程技术网

Python psycopg2传入表名

Python psycopg2传入表名,python,psycopg2,Python,Psycopg2,我有以下疑问 table = "#temp_table" cursor.execute("""select * from %s as a """, (table)) 我在from语句中不断遇到语法错误。为什么这不起作用?您收到此错误是因为传递到第二个参数table(实际上应该是table)中的参数在运行的SQL语句中被转义 在此示例中,将%s中的select*转换为“temp_table”中的select*,这是一个错误。要正确插入表名,需要直接将SQL语句字符串格式化,如下所示: query

我有以下疑问

table = "#temp_table"
cursor.execute("""select * from %s as a """, (table))

我在from语句中不断遇到语法错误。为什么这不起作用?

您收到此错误是因为传递到第二个参数table(实际上应该是table)中的参数在运行的SQL语句中被转义

在此示例中,将%s中的select*转换为“temp_table”中的select*,这是一个错误。要正确插入表名,需要直接将SQL语句字符串格式化,如下所示:

query = 'select * from "{}" as a'.format(table)
cursor.execute(query)

对于以这种方式插入到查询中的数据,您应该非常小心,因为它极易受到SQL注入攻击。不要将其用于不可信数据。

错误说明了什么?来自“temp_table”的语法错误@Just_一些家伙只是将其显式地放入sql语句中,而不是传递到args参数中,就像选择*from temp_table作为参数一样?我之所以想将其作为变量传入,是因为我有很多查询,除了从不同的表中提取外,它们都是完全相同的。我希望有一种方法可以循环浏览它们,只需更改表名。@just_Some_Guy,请查看编辑。您可以在循环中格式化查询。