我需要将SQL 2005数据库备份(使用C#)到* .bak文件。从该文件,我试图在同一个服务器上恢复到一个新的数据库。
备份工作正常,然后我的C#代码调用还原方法,它似乎工作,直到它最终“超时”。我检查了“innerExceptions”,他们发现RESTORE使它达到90%,然后返回异常。
以下是我用于备份和恢复的代码。
有人可以让我知道我哪里出错吗?它必须是我可以设置的某个超时参数,但我不知道它是什么或如何做。
public class JRBackupRestoreDB
{
public static void BackupDatabase(String databaseName, String userName, String password, String serverName, String destinationPath)
{
Backup sqlBackup = new Backup();
sqlBackup.Action = BackupActionType.Database;
sqlBackup.BackupSetDescription = "ArchiveDataBase:" + DateTime.Now.ToShortDateString();
sqlBackup.BackupSetName = "Archive";
sqlBackup.Database = databaseName;
BackupDeviceItem deviceItem = new BackupDeviceItem(destinationPath, DeviceType.File);
ServerConnection connection = new ServerConnection(serverName, userName, password);
Server sqlServer = new Server(connection);
Database db = sqlServer.Databases[databaseName];
sqlBackup.Initialize = true;
sqlBackup.Checksum = true;
sqlBackup.ContinueAfterError = true;
sqlBackup.Devices.Add(deviceItem);
sqlBackup.Incremental = false;
sqlBackup.ExpirationDate = DateTime.Now.AddDays(3);
sqlBackup.LogTruncation = BackupTruncateLogType.Truncate;
sqlBackup.FormatMedia = false;
sqlBackup.SqlBackup(sqlServer);
}
public static void RestoreDatabase(String databaseName, String filePath,
String serverName, String userName, String password,
String dataFilePath, String logFilePath)
{
Restore sqlRestore = new Restore();
BackupDeviceItem deviceItem = new BackupDeviceItem(filePath, DeviceType.File);
sqlRestore.Devices.Add(deviceItem);
sqlRestore.Database = databaseName;
ServerConnection connection = new ServerConnection(serverName, userName, password);
Server sqlServer = new Server(connection);
Database db = sqlServer.Databases[databaseName];
sqlRestore.Action = RestoreActionType.Database;
String dataFileLocation = dataFilePath + databaseName + ".mdf";
String logFileLocation = logFilePath + databaseName + "_Log.ldf";
db = sqlServer.Databases[databaseName];
RelocateFile rf = new RelocateFile(databaseName, dataFileLocation);
System.Data.DataTable logicalRestoreFiles = sqlRestore.ReadFileList(sqlServer);
sqlRestore.RelocateFiles.Add(new RelocateFile(logicalRestoreFiles.Rows[0][0].ToString(), dataFileLocation));
sqlRestore.RelocateFiles.Add(new RelocateFile(logicalRestoreFiles.Rows[1][0].ToString(), logFileLocation));
sqlRestore.SqlRestore(sqlServer);
db = sqlServer.Databases[databaseName];
db.SetOnline();
sqlServer.Refresh();
}
}
答案 0 :(得分:1)
您是否尝试使用ServerConnection.StatementTimeout
设置值以查看会发生什么?
MSDN参考here。
答案 1 :(得分:0)
这在普通的sql中很容易做到......
您是否考虑过这样尝试?您只需要编写sql脚本或过程来执行它然后运行它。这就是我们所做的(针对不同的情况,但类似):
backup database {{DATABASE NAME HERE}}
to disk = N'{{FILE_NAME_HERE}}'
with
name = N'{{BACKUP_DATABASE_NAME_HERE}}'
GO
restore database {{NEW_DATABASE_NAME}}
from disk = N'{{FILE_NAME_HERE}}'
with
file = 1
go