在Python中,使用SQLAlchemy,我想插入或更新一行。我试过这个:
existing = db.session.query(Toner)
for row in data:
new = Toner(row[0], row[1], row[2])
它不起作用。如何在new
表中插入或更新Toner
?我怀疑它已经完成了合并,但我无法理解如何做到这一点。
答案 0 :(得分:62)
假设某些列名......
插入一个
newToner = Toner(toner_id = 1,
toner_color = 'blue',
toner_hex = '#0F85FF')
dbsession.add(newToner)
dbsession.flush()
插入多个
newToner1 = Toner(toner_id = 1,
toner_color = 'blue',
toner_hex = '#0F85FF')
newToner2 = Toner(toner_id = 2,
toner_color = 'red',
toner_hex = '#F01731')
dbsession.add_all([newToner1, newToner2])
dbsession.flush()
<强>更新强>
q = dbsession.query(Toner)
q = q.filter(Toner.toner_id==1)
record = q.one()
record.toner_color = 'Azure Radiance'
dbsession.flush()
或使用MERGE
使用花哨的单行内容record = dbsession.merge(Toner( **kwargs))
答案 1 :(得分:2)
我尝试了很多方法,最后尝试了这一点:
def db_persist(func):
def persist(*args, **kwargs):
func(*args, **kwargs)
try:
session.commit()
logger.info("success calling db func: " + func.__name__)
return True
except SQLAlchemyError as e:
logger.error(e.args)
session.rollback()
return False
return persist
和:
@db_persist
def insert_or_update(table_object):
return session.merge(table_object)
答案 2 :(得分:2)
SQL:
INSERT INTO the_table (id, col1) VALUES (%s, %s) ON DUPLICATE KEY UPDATE col1 = %s
在py代码中:(用sqlalchemy 1.4.x测试,用mysql)
def test_insert_or_update():
insert_stmt = insert(the_table).values(
id = 'xxx',
col1 = 'insert value',
)
on_duplicate_key_stmt = insert_stmt.on_duplicate_key_update(
# col1 = insert_stmt.inserted.data,
col1 = 'update value',
col2 = 'mark'
)
print(on_duplicate_key_stmt)
session.execute(on_duplicate_key_stmt)
session.commit()