Question about transaction #1164
-
Hi, I'm executing (exec query) the stored procedure, which have the transaction inside. I'm setting autocommit to false, but when I see results it looks like the transaction is opened by PYODBC too.
Please first make sure you have looked at:
EnvironmentTo diagnose, we usually need to know the following, including version numbers. On Windows, be
IssueOften it is easiest to describe your issue as "expected behavior" and "observed behavior". |
Beta Was this translation helpful? Give feedback.
Replies: 3 comments
-
If you turn off autocommit, then it will create an explicit transaction that you need to commit manually. What is the actual problem the transaction is causing? |
Beta Was this translation helpful? Give feedback.
-
I have a transaction inside stored procedure, so it caused nested transaction... |
Beta Was this translation helpful? Give feedback.
-
Use import pyodbc
cnxn = pyodbc.connect(
"DSN=mssql_199;UID=scott;PWD=tiger^5HHH", autocommit=True
)
crsr = cnxn.cursor()
table_name = "discussion_1164"
crsr.execute(f"DROP TABLE IF EXISTS {table_name}")
crsr.execute(
f"CREATE TABLE {table_name} (id int primary key, txt varchar(50))"
)
crsr.execute(f"INSERT INTO {table_name} (id, txt) VALUES (1, 'original text')")
sql = f"""\
SET NOCOUNT ON;
BEGIN TRANSACTION;
UPDATE {table_name} SET txt = 'updated text' WHERE id = 1;
ROLLBACK;
BEGIN TRANSACTION;
INSERT INTO {table_name} (id, txt) VALUES (2, 'inserted text');
COMMIT;
"""
crsr.execute(sql)
print(crsr.execute(f"SELECT * FROM {table_name}").fetchall())
# [(1, 'original text'), (2, 'inserted text')] |
Beta Was this translation helpful? Give feedback.
Use
autocommit=True
. That will avoid the "outer" transaction and still allow the "inner" transaction(s) to work as expected: