执行使用SQL Alchemy连接的存储过程。

huangapple go评论62阅读模式
英文:

Execute Stored Procedure with SQL Alchemy Connection

问题

我想使用 SQL Alchemy 连接执行一个存储过程。在执行过程中没有出现错误,但数据库没有反映出任何更改。如果我直接在我的 Azure SQL Server 上运行存储过程,我会得到预期的结果(更新一个表)。

我尝试只运行该过程,得到了以下结果:

执行使用SQL Alchemy连接的存储过程。

有关它为什么不起作用的任何想法吗?我也愿意听取其他建议!我正在尝试在更新表后执行我的存储过程。

英文:

I want to execute a stored procedure using an SQL Alchemy Connection. I get no errors during execution, but no changes are reflected on the database. If I run the stored procedure directly on my Azure SQL Server, I get the expected results (which are updating a table).

I tried running just the procedure and get this:
执行使用SQL Alchemy连接的存储过程。

Any ideas on why it is not working?

I am also open to other ideas! I am trying to execute my stored procedure after upserting a table.

答案1

得分: 1

使用 conn.commit() 来提交对数据库的更改,然后使用 conn.close() 来结束连接。

实现代码:

import sqlite3
conn = sqlite3.connect('database.sqlite3')
conn.execute("insert into Users Values('email', 'password')")
conn.commit()
conn.close()
英文:

use 'conn.commit()' to commit changes to the db
then use 'conn.close()' to end the connection

Implementation:

import sqlite3
conn = sqlite3.connect('database.sqlite3')
conn.execute(f"insert into Users Values('email', 'password')")
conn.commit()
conn.close()

答案2

得分: 1

The recommended approach for current versions of SQLAlchemy is to use a context manager (with block) to begin() the transaction. When the context manager exits the transaction will automatically be committed unless an error has occurred:

with engine.begin() as conn:
    conn.exec_driver_sql("EXEC my_stored_procedure")

Bonus tip: Naming stored procedures with an sp_ prefix is discouraged because it can lead to confusion with SQL Server's built-in "system procedures". More details here:

https://sqlperformance.com/2012/10/t-sql-queries/sp_prefix

英文:

The recommended approach for current versions of SQLAlchemy is to use a context manager (with block) to begin() the transaction. When the context manager exits the transaction will automatically be committed unless an error has occurred:

with engine.begin() as conn:
    conn.exec_driver_sql("EXEC my_stored_procedure")

Bonus tip: Naming stored procedures with an sp_ prefix is discouraged because it can lead to confusion with SQL Server's built-in "system procedures". More details here:

https://sqlperformance.com/2012/10/t-sql-queries/sp_prefix

huangapple
  • 本文由 发表于 2023年5月26日 00:01:03
  • 转载请务必保留本文链接:https://go.coder-hub.com/76334256.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定