无法在事务内还原;自动提交已开启

时间:2019-03-05 19:59:14

标签: sqlalchemy

我正在将sqlalchemypyodbc一起使用来还原mssql“ .bak”文件。我遵循了先前posts提出的有关解决交易的建议,但似乎并没有改变任何东西。任何帮助将不胜感激。

from urllib.parse import quote_plus
from sqlalchemy import create_engine

params = quote_plus("Driver={SQL Server Native Client 11.0};"
                    "Server=Computer\SQLEXPRESS;"
                    "Database=master;"
                    "Trusted_Connection=yes;")

engine = create_engine("mssql+pyodbc:///?odbc_connect=%s" % params)
connection = engine.raw_connection()

db_path = r"C:\\Path\\to\\OutputDB.bak"
move_path = r"C:\\Path\\to\\backup\\db.mdf"
move_log_path = r"C:\\Path\\to\\backup\\db_Log.ldf"

sql_cmd = f"""
    RESTORE DATABASE [db]
    FROM DISK = N'{db_path}'
    WITH FILE = 1,
    MOVE N'db'
    TO N'{move_path}',
    MOVE N'test_log'
    TO N'{move_log_path}',
    RECOVERY,
    NOUNLOAD,
    REPLACE,
    STATS = 5
"""


connection.autocommit = True

cursor = connection.cursor()

cursor.execute(sql_cmd)
while cursor.nextset():
    pass

connection.autocommit = False

我收到以下错误消息:

  

ProgrammingError :(“ 42000”,“ [42000] [Microsoft] [SQL Server Native Client 11.0] [SQL Server]无法在事务内执行备份或还原操作。(3021)(SQLExecDirectW); [42000] [ Microsoft] [SQL Server Native Client 11.0] [SQL Server] RESTORE DATABASE异常终止。(3013)')

1 个答案:

答案 0 :(得分:0)

我设法通过将connect_args={'autocommit': True}传递给create_engine来解决此问题。 cursor.execute(sql_cmd).execution_options(autocommit=True)connection.autocommit = True都没有起作用。

from urllib.parse import quote_plus
from sqlalchemy import create_engine

params = quote_plus("Driver={SQL Server Native Client 11.0};"
                    "Server=Computer\SQLEXPRESS;"
                    "Database=master;"
                    "Trusted_Connection=yes;")

engine = create_engine("mssql+pyodbc:///?odbc_connect=%s" % params, connect_args={'autocommit': True})
connection = engine.raw_connection()

db_path = r"C:\\Path\\to\\OutputDB.bak"
move_path = r"C:\\Path\\to\\backup\\db.mdf"
move_log_path = r"C:\\Path\\to\\backup\\db_Log.ldf"

sql_cmd = f"""
    RESTORE DATABASE [db]
    FROM DISK = N'{db_path}'
    WITH FILE = 1,
    MOVE N'db'
    TO N'{move_path}',
    MOVE N'test_log'
    TO N'{move_log_path}',
    RECOVERY,
    NOUNLOAD,
    REPLACE,
    STATS = 5
"""

cursor = connection.cursor()

cursor.execute(sql_cmd)
while cursor.nextset():
    pass