Cannot perform a backup or restore operation within a transaction

前端 未结 3 1485
一整个雨季
一整个雨季 2020-12-19 15:12

I am using PyODBC to back up my database, using following code:

SQL_command = """
                BACKUP DATABASE [MyDatabase]
                         


        
相关标签:
3条回答
  • 2020-12-19 15:28

    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.

    0 讨论(0)
  • 2020-12-19 15:31

    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()
    
    0 讨论(0)
  • 2020-12-19 15:37

    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
    
    0 讨论(0)
提交回复
热议问题