2

Pythonでpostgresクエリを実行したいのですが、テーブル名をパラメータとして渡す必要があります。テーブルは実行時に作成されるためです。dict query param styleを使用しましたが、エラーが発生します。

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

1 に答える 1

3

PREPARE送信するステートメントは、dの場合に構文的に有効である必要がありますが、テーブル名のプレースホルダーを含むステートメントは無効です。プリペアドステートメントのテーブル名にプレースホルダーを使用することはできません。

オプションは次のとおりです。

  • テーブル名を通常の文字列置換で置き換え"double quoted"ます。引用ルーチンには十分注意してください。テーブル名内の引用符がそれ自体で2倍になるようにして、テーブル名が。にdouble"quoteなるようにしてください"double""quote"。例えば。'SELECT * FROM "%s"' % quote_ident(tablename)quote_identAFAIK psycopg2はそのような関数を公開しないため、自分でロールする必要があります。

  • EXECUTE ... USINGテーブル名を使用して動的SQL文を作成するために使用するPL/PgSQL関数にクエリパラメータとしてテーブル名を送信します。PL / PgSQLはこのquote_ident関数を使用して、ホームロール実装よりも安全な見積もりを提供できます。

于 2012-10-11T11:58:29.013 に答える