简体   繁体   English

存储过程未使用 sqlalchemy/pyodbc 提交

[英]stored proc not committing with sqlalchemy/pyodbc

I am using sqlalchemy/pyodbc to connect to a MS SQL 2012 server.我正在使用 sqlalchemy/pyodbc 连接到 MS SQL 2012 服务器。 I chose sqlalchemy because of the direct integration with pandas dataframes using .read_sql and .to_sql .我之所以选择 sqlalchemy,是因为它使用.read_sql.to_sql.to_sql数据帧直接集成。

At a high level, my code is:在高层次上,我的代码是:

df = dataframe.read_sql("EXEC sp_getsomedata")
<do some stuff here>
finaldf.to_sql("loader_table", engine,...)

This part works great, very easy to read, etc. The problem is that I have to run a final stored proc to insert the data from the loader table into the live table.这部分很好用,很容易阅读等等。问题是我必须运行一个最终存储过程来将加载器表中的数据插入到实时表中。 Normally, sqlalchemy knows to commit after INSERT/UPDATE/DELETE, but doesn't want to do the commit for me when I run this final stored proc.通常,sqlalchemy 知道在 INSERT/UPDATE/DELETE 之后提交,但是当我运行这个最终存储过程时不想为我做提交。

After having tried multiple approaches, I see the transaction in the db sitting uncommitted.在尝试了多种方法后,我看到 db 中的事务未提交。 I know sqlalchemy is very flexible and I am using about 3% of its functionality, what is the simplest way to get this working?我知道 sqlalchemy 非常灵活,我使用了它大约 3% 的功能,最简单的方法是什么? I think I need to be using sqlalchemy core and not ORM.我想我需要使用 sqlalchemy 核心而不是 ORM。 I saw examples using sessionmaker, but I think that monopolizes the engine object and doesn't let pandas access it.我看到了使用 sessionmaker 的例子,但我认为它垄断了引擎对象并且不允许熊猫访问它。

connection = engine.connect()
transaction = connection.begin()
connection.execute("EXEC sp_doLoaderStuff")
transaction.commit()
connection.close()

I have tried calling .execute from the connection level, from a cursor level, and even using the .raw_connection() method without success.我曾尝试从连接级别、游标级别甚至使用.raw_connection()方法调用.execute ,但没有成功。

connection = engine.raw_connection()
connection.autocommit = True
cursor = connection.cursor()
cursor.execute("EXEC sp_doLoaderStuff")
connection.commit()
connection.close()

Any ideas what I am missing here?任何想法我在这里缺少什么?

Completely self-inflicted.完全自作自受。 The correct working code using the raw_connection() method that is working fine is:使用正常工作的 raw_connection() 方法的正确工作代码是:

connection = engine.raw_connection()
cursor = connection.cursor()
cursor.execute("EXEC sp_doLoaderStuff")
connection.commit()
connection.close()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM