sqlalchemy with postgres:插入一个表中有圆括号的表

时间:2014-09-18 16:20:15

标签: python postgresql sqlalchemy psycopg2

假设您在postgres中有一个表"foo",其列名为"col (parens) name"。 psql命令

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

工作得很好。但是,如果我尝试使用sqlalchemy(版本0.9.7)执行相同操作,则生成的python代码将失败:

conn = sqlalchemy.create_engine('postgresql://name:password@host: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'

显然,用于绑定db参数的sqlalchemy方法遇到了python字符串插值问题。有关解决方法的任何建议吗?

1 个答案:

答案 0 :(得分:1)

paramstyle="format"添加到create_engine来电。它将改变查询值插入查询的方式,使其在关闭括号时不会崩溃。

conn = sqlalchemy.create_engine(
    'postgresql://name:password@host:port/database',
     paramstyle="format"
)