SQLAlchemy-MySQL-ON-DUPLICATE-KEY更新

2024-04-20 07:22:09 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试使用SQLALchemy MySQL ON \u DUPLICATE \u KEY \u UPDATE()函数,但它没有按预期工作。你知道吗

from sqlalchemy.dialects.mysql.dml import Insert 

new_record={'id': 'val1', 'col1': 'new val'}

# Here id is the primary key
# my_table is a Table object
Insert(my_table).on_duplicate_key_update(new_record)

此代码工作时不会抛出错误,但表中主键值为'val1'的现有记录不会被更新。你知道吗

我查阅了有关on duplicate key update的SQLAlchemy文档,但不知道如何调用该函数。你知道吗


Tags: key函数idnewsqlalchemyisonmy
1条回答
网友
1楼 · 发布于 2024-04-20 07:22:09

首先要注意的是,您只创建并丢弃了一个insert语句对象。为了执行它,您必须将它传递给SQLAlchemy的execute()方法之一。语句还缺少要首先尝试和插入的值。你知道吗

from sqlalchemy.dialects.mysql.dml import Insert 

new_record = {'id': 'val1', 'col1': 'new val'}

# Here id is the primary key
# my_table is a Table object
stmt = Insert(my_table).values(new_record)
stmt = stmt.on_duplicate_key_update(col1=stmt.inserted.col1)

# This will actually execute the statement
engine.execute(stmt)

相关问题 更多 >