【问题标题】:Return primary key of inserted row using SQLAlchemy & SQL Server使用 SQLAlchemy 和 SQL Server 返回插入行的主键
【发布时间】:2021-08-21 02:45:16
【问题描述】:

我正在尝试插入一行并保留主键以供下游应用程序使用。我似乎无法在 SQLAlchemy 中检索值,但在我的数据库管理系统中似乎可以正常工作。

这是基本代码

sql = """
INSERT INTO [workflow_execution_status]([workflow], [requested_by], [requested_datetime], [experiment_id])
OUTPUT Inserted.execution_id 
VALUES (?, ?, ?, ?)
"""

with engine.connect() as connection:
    result = connection.execute(sql, ('test_workflow', 'test_user', datetime.datetime.now(), 0))
    for row in result:
        print(row)

但这是我收到的错误:

DBAPIError: (pyodbc.Error) ('HY010', '[HY010] [Microsoft][ODBC Driver 13 for SQL Server]函数序列错误 (0) (SQLFetch)')

我猜我用 SQLAlchemy 做错了——希望有人能指出我正确的方向。

【问题讨论】:

  • 驱动程序可能对插入操作的初始行数感到困惑。如果你使用set nocount on; INSERT INTO ...会更好吗?

标签: python sql sql-server sqlalchemy


【解决方案1】:

AlwaysLearning 的解决方案是正确的。附加“SET NOCOUNT ON;”到查询的顶部,例如

sql = """
SET NOCOUNT ON;
INSERT INTO [workflow_execution_status]([workflow], [requested_by], [requested_datetime], [experiment_id])
OUTPUT Inserted.execution_id 
VALUES (?, ?, ?, ?)"""

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-01-18
    • 1970-01-01
    • 1970-01-01
    • 2018-04-18
    • 1970-01-01
    • 1970-01-01
    • 2011-10-11
    • 1970-01-01
    相关资源
    最近更新 更多