我想从.dat文件恢复MS SQL数据库。
我通过在Windows PowerShell上调用以下命令/语句或将其保存在.bat文件中并运行文件本身来成功完成:
sqlcmd -S POLIVEIRA-PC\MSSQLSERVER2008 -Q "RESTORE DATABASE [Odemira_2012-07-01_021501] FROM DISK=N'C:\Program Files\Microsoft SQL Server\MSSQL10_50.MSSQLSERVER2008\MSSQL\Backup\ODEMIRA2013\Odemira_2012-07-01_021501' WITH FILE=1, MOVE N'Odemira_Data' TO N'C:\Program Files\Microsoft SQL Server\MSSQL10_50.MSSQLSERVER2008\MSSQL\DATA\Odemira_2012-07-01_021501.MDF', MOVE N'Odemira_Log' TO N'C:\Program Files\Microsoft SQL Server\MSSQL10_50.MSSQLSERVER2008\MSSQL\DATA\Odemira_2012-07-01_021501_1.LDF', NOUNLOAD, STATS=10"
但是,由于我需要使用不同的数据库多次重复此指令,因此我想使用Python在循环中执行此操作。我试图使用子进程模块来复制上面的指令。 Unsuccessefully。
我的Python代码如下:
import subprocess
host = 'POLIVEIRA-PC\\MSSQLSERVER2008'
mssql_dir = 'C:\\Program Files\\Microsoft SQL Server\\MSSQL10_50.MSSQLSERVER2008\\MSSQL\\DATA\\'
db_dir = 'C:\\Program Files\\Microsoft SQL Server\\MSSQL10_50.MSSQLSERVER2008\\MSSQL\\Backup\\ODEMIRA2013\\'
db = 'Odemira_2012-07-01_021501'
statement = '"RESTORE DATABASE [' + db + '] FROM DISK=N\'' + db_dir + \
db + '\' WITH FILE=1, MOVE N\'Odemira_Data\' TO N\'' + mssql_dir + \
db + '.MDF\', MOVE N\'Odemira_Log\' TO N\'' + mssql_dir + \
db + '_1.LDF\', NOUNLOAD, STATS=10"'
subprocess.call(["sqlcmd", "-S", host, "-Q", statement])
当我在Windows PowerShell上运行此python脚本时,出现以下错误:
PS C:\Users\POliveira\Dropbox\Academia\IST\Dissertacao_de_Mestrado\SQL> python .\lib\temp.py
Sqlcmd: 'RESTORE DATABASE [Odemira_2012-07-01_021501] FROM DISK=N'C:\Program Files\Microsoft SQL Server\MSSQL10_50.MSSQLSERVER2008\MSSQL\Backup\ODEMIRA2013\Odemira_2012-07-01_021501' WITH FILE=1, MOVE N'Odemira_Data' TO N'C:\Program Files\Microsoft SQL Server\MSSQL10_50.MSSQLSERVER2008\MSSQL\DATA\Odemira_2012-07-01_021501.MDF', MOVE N'Odemira_Log' TO N'C:\Program Files\Microsoft SQL Server\MSSQL10_50.MSSQLSERVER2008\MSSQL\DATA\Odemira_2012-07-01_021501_1.LDF', NOUNLOAD, STATS=10\""': Unexpected argument. Enter '-?' for help.
我不知道我错过了什么。我已经尝试使用后退来转义双引号(“RESTORE ... 10”),但它也没有用。
编辑:我确实尝试在subprocess.call上添加标志shell = True,但我以相同的错误结束了。
答案 0 :(得分:3)
删除语句周围的双引号,如下所示:
statement = 'RESTORE DATABASE [' + db + '] FROM DISK=N\'' + db_dir + \
db + '\' WITH FILE=1, MOVE N\'Odemira_Data\' TO N\'' + mssql_dir + \
db + '.MDF\', MOVE N\'Odemira_Log\' TO N\'' + mssql_dir + \
db + '_1.LDF\', NOUNLOAD, STATS=10'