6

How can I execute sql server transaction using pyodbc(python)?

I know there is a method "execute" for one string and one arguments' list.

But now I want to execute 2 or more commands in one transaction like this.

Is there a method to do that?

BEGIN TRANSACTION [Tran1]

BEGIN TRY

INSERT INTO [Test].[dbo].[T1]
  ([Title], [AVG])
VALUES ('Tidd130', 130), ('Tidd230', 230)

UPDATE [Test].[dbo].[T1]
  SET [Title] = N'az2' ,[AVG] = 1
WHERE [dbo].[T1].[Title] = N'az'


COMMIT TRANSACTION [Tran1]

END TRY
BEGIN CATCH
  ROLLBACK TRANSACTION [Tran1]
END CATCH  

GO

1 Answer 1

10

When you create a connection object, you can tell it not to commit every command you execute. Then, when you have executed all the commands you wanted, you can commit them all in one transaction.

myconnection = pyodbc.connect(myconnectionstring, autocommit=False)
# your commands here
myconnection.commit()
Sign up to request clarification or add additional context in comments.

2 Comments

would the "commands" be just individual .execute() statements with each different SQL statement?
yes @SourceMatters

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.