通过python在postgres中将表名作为参数传递
我想用python执行postgres查询。表名必须作为参数传递。因为表将在运行时创建。我使用了dict query param样式。但是我得到了一个错误通过python在postgres中将表名作为参数传递,python,postgresql,Python,Postgresql,我想用python执行postgres查询。表名必须作为参数传递。因为表将在运行时创建。我使用了dict query param样式。但是我得到了一个错误 import psycopg2 CONNECTION_STRING = "dbname='autogist' user='postgres' password=''" query = "INSERT INTO %(table)s " +\ "(vin_id, vin_details_id, price, mil
import psycopg2
CONNECTION_STRING = "dbname='autogist' user='postgres' password=''"
query = "INSERT INTO %(table)s " +\
"(vin_id, vin_details_id, price, mileage, dealer_id, created_on, modified_on) " +\
"VALUES (%(vin_id)s, %(vlookup_id)s, %(price)s, %(mileage)s, %(dealer_id)s,now(),now()) " +\
"RETURNING id"
params = {"table" : "dealer_vehicle_details_2010_01_02",\
"vin_id":"3",\
"vlookup_id":"403",\
"price":"403",\
"mileage":"403",\
"dealer_id":"276092"
}
conn=psycopg2.connect(CONNECTION_STRING)
cursor = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)
cursor.execute(query,params)
回溯:
ERROR: An unexpected error occurred while tokenizing input
The following traceback may be corrupted or invalid
The error message is: ('EOF in multi-line statement', (262, 0))
---------------------------------------------------------------------------
ProgrammingError Traceback (most recent call last)
/home/gridlex/workspace/<ipython console> in <module>()
/usr/local/lib/python2.6/dist-packages/psycopg2/extras.pyc in execute(self, query, vars)
121 self.index = {}
122 self._query_executed = 1
--> 123 return _cursor.execute(self, query, vars)
124
125 def callproc(self, procname, vars=None):
ProgrammingError: syntax error at or near "E'dealer_vehicle_details_2010_01_02'"
LINE 1: INSERT INTO E'dealer_vehicle_details_2010_01_02' (vin_id, vi...
您发送的语句在准备时必须在语法上有效,而带有表名占位符的语句则无效。在准备好的语句中,不能对表名使用占位符 你的选择是: 用双引号的常规字符串替换替换中的表名。要非常小心你的报价程序;确保将表名中的任何引号加倍,使表名doublequote变为doublequote。例如,“从%s中选择*”\u identtablename。您必须使用自己的quote_ident,因为AFAIK psycopg2不会公开这样的函数 将表名作为查询参数发送到使用EXECUTE。。。用于使用表名创建动态SQL语句。PL/PgSQL可以使用quote_ident函数提供比自滚实现更安全的报价
cursor.mogrifyquery,参数插入E'dealer_vehicle_details_2010_01_02'vin_id,vin_details_id,价格,里程,dealer_id,创建,修改值E'3',E'403',E'403',E'403',E'276092',现在,返回id