在插入表时处理SQLAlchemy中的触发器

时间:2017-11-27 14:44:46

标签: python sql-server-2008 sqlalchemy flask-sqlalchemy

我使用flask-SQLAlchemy来映射数据库中名为Proposal的表之一,但是当从应用程序插入数据库时​​遇到了问题。这是错误:

sqlalchemy.exc.ProgrammingError: (pyodbc.ProgrammingError) ('42000', "[42000]

[Microsoft][ODBC SQL Server Driver][SQL Server]The target table 'Proposal' of
the DML statement cannot have any enabled triggers if the statement contain an
OUTPUT clause without INTO clause. (334) (SQLExecDirectW); [42000] [Microsoft]
[ODBC SQL Server Driver][SQL Server]Statement(s) could not be prepared

数据库属于MSSQL类型。

SQLAlchemy生成的sql语句是

SQL: 'INSERT INTO [Proposal] (proposal_fee, contract1, contract,
proposal_disb, source, sid, value_per_hr, team_hrs, reason_for_loss,
incharge, [Country_id], [manner], [Manager_id], preparer_id,
task_id, date_received, proposal_deadline, industry_id,
proposal_currency_id, contract_currency_id, service_description_id,
business_unit_id, status_id, associated_cost) OUTPUT inserted.[ID] VALUE
(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)']
[parameters: ('', '', '', '', '', 'None', '', '', None, 'Adv,
Office', 'Select Country', None, 'ABCD', 'some name', '1007000', '', '', '', '', 'usd', None, None, '', '')]

我知道当我禁用触发器时,插入操作会起作用,但我需要sqlalchemy中的解决方案来解决这个问题吗?

有什么办法吗?

2 个答案:

答案 0 :(得分:1)

我意识到我必须删除该输出子句并找到了推荐的解决方案:

__table_args__ = {'implicit_returning':False}

为Proposal表创建类时。

答案 1 :(得分:0)

如果要映射到您的表类,这将无效。对于SqlAlchemy 1.2.7,可以通过为implicit_returning设置arg inline=True来关闭insert()documentation - 检查"输入" arg插入部分)。

这是我的实现,它还利用sessionmaker来运行查询:

from sqlalchemy.orm import mapper, sessionmaker
from sqlalchemy import MetaData, create_engine, Table

class User(object):
    pass

def CreateUser(event):
    #Retrieve event
    email = event["email"]
    firstName = event["firstName"]
    lastName = event["lastName"]

    #Create connection
    conn_str = "mssql+pymssql://<username>:<password>@<rds_host>:1433/<db_name>"
    engine = create_engine(conn_str)
    metadata = MetaData(engine, reflect=True)

    #Create session
    Session = sessionmaker()
    Session.configure(bind=engine)
    session = Session()

    #Retrieve DB table
    users = Table("tblUser", metadata, autoload=True)
    mapper(User, users)

    #Insert record
    isInline = True
    insert = users.insert(None, isInline).values(FirstName=firstName, LastName=lastName, Email=email)
    session.execute(insert)
    session.commit()