【问题标题】:why the stored procedure called from sqlalchemy is not working but calling from workbench is working?为什么从 sqlalchemy 调用的存储过程不工作,但从工作台调用是工作?
【发布时间】:2020-03-18 03:25:02
【问题描述】:

我有一个存储过程。

通过 MySQL 工作台调用它,如下工作;

CALL `lobdcapi`.`escalatelobalarm`('A0001');

但不是来自 python 程序。 (意味着它没有抛出任何异常,进程以静默方式完成执行)如果我在列名中犯了任何错误,那么在 python 中我会得到一个错误。所以它调用我的存储过程但没有按预期工作。 (这是一个更新查询。它需要安全更新)

为什么通过python sqlalchemy 这次更新没有更新任何记录?

CREATE DEFINER=`lob`@`%` PROCEDURE `escalatelobalarm`(IN client_id varchar(50))
BEGIN

 SET SQL_SAFE_UPDATES = 0;                                   
update lobdcapi.alarms
    set lobalarmescalated=1
where id in (

    SELECT al.id 
    from (select id,alarmoccurredhistoryid from lobdcapi.alarms where lobalarmpriorityid=1 and lobalarmescalated=0 and clientid=client_id 
            and alarmstatenumber='02' ) as al
    inner join lobdcapi.`alarmhistory` as hi on hi.id=al.alarmoccurredhistoryid
            and hi.datetimestamp<=  current_timestamp() )

);

SET SQL_SAFE_UPDATES = 1;

END

我这样称呼它;

from sqlalchemy import and_, func,text


db.session.execute(text("CALL escalatelobalarm(:param)"), {'param': clientid})

我怀疑我通过代码传递的参数没有正确绑定?

【问题讨论】:

  • 这能回答你的问题吗? stored procedures with sqlAlchemy
  • @YugandharChaudhari 我得到了 Krik 的回答。这很简单,我没有使用 session.commit 是问题

标签: python mysql sqlalchemy flask-sqlalchemy


【解决方案1】:

我没有从 SQLAlchemy 调用存储过程,但它似乎可能在事务中,因为您正在使用会话。也许最后打电话给db.session.commit()会有所帮助?

如果失败,SQLAlchemy 在此处调用calling stored procs。也许试试他们使用callproc的方法。适应您的用例,例如:

connection = db.session.connection()
try:
    cursor = connection.cursor()
    cursor.callproc("escalatelobalarm", [clientid])
    results = list(cursor.fetchall())
    cursor.close()
    connection.commit()
finally:
    connection.close()

【讨论】:

  • 非常感谢,db.session.commit() 解决了这个问题
猜你喜欢
  • 1970-01-01
  • 2019-08-10
  • 2019-02-06
  • 1970-01-01
  • 1970-01-01
  • 2021-10-31
  • 2011-06-08
  • 1970-01-01
  • 2017-11-02
相关资源
最近更新 更多