2014-09-18 68 views
3

假設在postgres中有一個表"foo",列名爲"col (parens) name"。 psql命令帶postgres的sqlalchemy:插入列中有圓括號的表中

INSERT INTO "foo" ("col (parens) name") VALUES ('bar'); 

工作得很好。但是,如果我嘗試做使用SQLAlchemy的相同(0.9.7版本),產生的Python代碼失敗:

conn = sqlalchemy.create_engine('postgresql://name:[email protected]:port/database') 
meta = sqlalchemy.schema.MetaData() 
meta.reflect(bind=conn) 
foo = meta.tables['foo'] 
vals = [{'col (parens) name': 'hi'}, {'col (parens) name': 'bye'}] 
conn.execute(foo.insert(values=vals)) 

這不起作用,給了以下錯誤:

Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
    File "sqlalchemy/engine/base.py", line 729, in execute 
    return meth(self, multiparams, params) 
    File "sqlalchemy/sql/elements.py", line 321, in _execute_on_connection 
    return connection._execute_clauseelement(self, multiparams, params) 
    File "sqlalchemy/engine/base.py", line 826, in _execute_clauseelement 
    compiled_sql, distilled_params 
    File "sqlalchemy/engine/base.py", line 957, in _execute_context 
    context) 
    File "sqlalchemy/engine/base.py", line 1162, in _handle_dbapi_exception 
    util.reraise(*exc_info) 
    File "sqlalchemy/engine/base.py", line 950, in _execute_context 
    context) 
    File "sqlalchemy/engine/default.py", line 436, in do_execute 
    cursor.execute(statement, parameters) 
KeyError: 'col (parens' 

顯然,用於綁定數據庫參數的sqlalchemy方法在使用python字符串插值時遇到了麻煩。任何解決方法的建議?

回答

0

paramstyle="format"添加到create_engine調用中。它將改變查詢值插入查詢的方式,使其不會在右括號上崩潰。

conn = sqlalchemy.create_engine(
    'postgresql://name:[email protected]:port/database', 
    paramstyle="format" 
) 
相關問題