通过python将表名作为参数传递给postgres

时间:2012-10-11 11:48:02

标签: python postgresql

我想在python中执行postgres查询。表名必须作为参数传递。因为表将在运行时创建。我使用了dict查询参数样式。但是我收到了错误。

 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)

TRACEBACK:

 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...

1 个答案:

答案 0 :(得分:3)

PREPARE d时,您发送的语句必须在语法上有效,而表名的占位符的语句不是。您不能在预准备语句中使用占位符作为表名。

您的选择是:

  • 使用常规字符串替换"double quoted"替换表名。你的引用程序要非常小心;确保它将自己的表名称中的任何引号加倍,因此表名double"quote变为"double""quote"。例如。 'SELECT * FROM "%s"' % quote_ident(tablename)。你必须推出自己的quote_ident,因为AFAIK psycopg2不会公开这样的函数。

  • 将表名作为查询参数发送到PL / PgSQL函数,该函数使用EXECUTE ... USING使用表名创建动态SQL语句。 PL / PgSQL可以使用quote_ident函数来提供比自制实现更安全的引用。