Lum*_*mpy 4 sql-server python sql-server-2017
我正在尝试使用 python 来自动化我们的一些数据库恢复。当我运行 SQL 查询时,数据库会恢复并正常恢复,但是当我运行使用相同 SQL 查询的 python 脚本时,数据库仍处于恢复模式。
对我做错的任何帮助将不胜感激。
import pyodbc
#Set these Variables
sourceserver = 'MySourceServerName'
destinationserver = 'MyDestinationServerName'
dbname = 'test'
sourceserverplusport = sourceserver + ',1433'
destinationserverplusport = destinationserver + ',1433'
def ExecSQL(serverplusport, dbnameIN, sql):
try:
connexecsql = pyodbc.connect('Driver={SQL Server};'
'Server=' + serverplusport +';'
'Database=' + dbnameIN + ';'
'Trusted_Connection=yes;')
#Set AutoCommit
if connexecsql is not None:
connexecsql.autocommit = True
print(sql)
cursor = connexecsql.cursor()
cursor.execute(sql)
finally:
cursor.commit
cursor.close
connexecsql.commit
connexecsql.close
sqlcommand = r"""IF @@SERVERNAME = 'MyDestinationServerName'
RESTORE DATABASE test FROM DISK = '\\MyBackupPath\test.BAK' WITH FILE = 1, MOVE N'test' to N'X:\Database\MDF\test.mdf', MOVE N'test_log' to N'Y:\Database\LDF\test_log.ldf', NOUNLOAD, REPLACE, RECOVERY, STATS = 5;"""
ExecSQL(destinationserverplusport, "master", sqlcommand)
Run Code Online (Sandbox Code Playgroud)
如果我ExecSQL
在脚本末尾再添加一个命令以在最后运行会RESTORE DATABASE test WITH RECOVERY;
返回错误:
无法恢复数据库,因为日志未恢复。”
包括REPLACE
与RECOVERY
消除错误,但叶子仍然恢复数据库。
Pyodbc 不会自动处理过去的信息消息,并且 RESTORE 会生成很多信息。因此,您必须使用它们来处理它们,cursor.nextset()
否则您实际上是在 RESTOREcursor.close()
实际完成之前通过运行来中止它。
例如
cursor.execute(sql)
while cursor.nextset():
pass
cursor.close()
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
371 次 |
最近记录: |