ASP.NET利用SQLDMO实现数据库的备份与恢复下篇
Admin | 2008-1-13 18:51:58 | 被阅次数 | 6791
②:实现数据库恢复代码(注意:在恢复时要注意先杀掉当前数据库的所有进程):
public string DbRestore() //恢复代码
{
if(exepro()!=true)//执行存储过程
{
return "操作失败";
}
else
{
SQLDMO.Restore oRestore = new SQLDMO.RestoreClass();
SQLDMO.SQLServer oSQLServer = new SQLDMO.SQLServerClass();
try
{
exepro();
oSQLServer.LoginSecure = false;
oSQLServer.Connect(server, uid, pwd);
oRestore.Action = SQLDMO.SQLDMO_RESTORE_TYPE.SQLDMORestore_Database;
oRestore.Database = database;
/**////自行修改
oRestore.Files = @"d:\aaa\aaa.bak";
oRestore.FileNumber = 1;
oRestore.ReplaceDatabase = true;
oRestore.SQLRestore(oSQLServer);
return "ok";
}
catch(Exception e)
{
return "恢复数据库失败";
throw e;
}
finally
{
oSQLServer.DisConnect();
}
}
}
/**////
/// 杀死当前库的所有进程
///
///
private bool exepro()
{
SqlConnection conn1 = new SqlConnection("server="+server+";uid="+uid+";pwd="+pwd+";database=master");
SqlCommand cmd = new SqlCommand("killspid",conn1);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("@dbname","aaa");
try
{
conn1.Open();
cmd.ExecuteNonQuery();
return true;
}
catch(Exception ex)
{
return false;
}
finally
{
conn1.Close();
}
}