小编Tro*_*lin的帖子

如何在postgresql上使用sqlalchemy进行正确的upsert?

我想使用sqlalchemy核心使用postgresql 9.5添加的"新"功能进行upsert.虽然它已经实现,但我对语法很困惑,我无法适应我的需求.以下是我希望能够做的示例代码:

from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
class User(Base):
__tablename__ = 'test'
a_id = Column('id',Integer, primary_key=True)
a = Column("a",Integer)

engine = create_engine('postgres://name:password@localhost/test')
User().metadata.create_all(engine)
meta = MetaData(engine)
meta.reflect()
table = Table('test', meta, autoload=True)
conn = engine.connect()

from sqlalchemy.dialects.postgresql import insert as psql_insert
stmt = psql_insert(table).values({table.c['id']: bindparam('id'),
          table.c['a']: bindparam('a')})
stmt = stmt.on_conflict_do_update(
    index_elements=[table.c['id']],
    set_={'a': bindparam('a')})
list_of_dictionary = [{'id':1, 'a':1, }, {'id':2, 'a':2,}]
conn.execute(stmt, list_of_dictionary)
Run Code Online (Sandbox Code Playgroud)

我基本上想要插入大量的行,如果已经有一个id,我想用我初始想要插入的值来更新它.但sqlalchemy给我这个错误:

CompileError: bindparam() name 'a' is reserved for automatic usage in the VALUES or SET clause …
Run Code Online (Sandbox Code Playgroud)

python postgresql sqlalchemy

8
推荐指数
1
解决办法
5610
查看次数

标签 统计

postgresql ×1

python ×1

sqlalchemy ×1