I am using PyODBC to back up my database, using following code:
SQL_command = """
BACKUP DATABASE [MyDatabase]
Your error says
Cannot perform a backup or restore operation within a transaction.
Transactions are started by default in pyodbc, so how do you execute a query without creating a transaction? Simply turn on autocommit:
conn.autocommit = true
// do stuff
conn.autocommit = false
The pyodbc FAQ has an entry about this.
The other answers are correct. You do need to set autocommit. However, the transaction will complete but the backup won't actually be taken because of a quirk in SQL Server and the way it returns status messages for backup and restore operations.
To work around this you need to loop through these return messages until none remain:
SQL_command = """
BACKUP DATABASE [MyDatabase]
TO DISK = N'D:\MSSQL\BACKUP\MyDatabase_20141212.bak' WITH
NOFORMAT
, NOINIT
, NAME = N'MyDatabase_20141212'
, SKIP
, REWIND
, NOUNLOAD
, STATS = 10
"""
conn.cursor.execute(SQL_command)
while conn.cursor.nextset():
pass
conn.cursor.close()
By default all pyodbc connections start with a transaction.
You need to turn autocommit on - using the autocommit keyword to the connect function:
conn.autocommit = true