成功了,把代码帖出来给
大家看看,跟我刚开始帖出来的差不多,是需要杀掉进程的,我之前调用的存储过程,可能有点问题,现在改成sql了
/// <summary>
/// 数据库备份
/// </summary>
public static int DbBackup(string serverip, string username, string psw, string path)
{
int ret;
SQLDMO.Backup oBackup = new SQLDMO.BackupClass();
SQLDMO.SQLServer oSQLServer = new SQLDMO.SQLServerClass();
try
{
oSQLServer.LoginSecure = false;
oSQLServer.Connect(serverip, username, psw);
oBackup.Action = SQLDMO.SQLDMO_BACKUP_TYPE.SQLDMOBackup_Database;
oBackup.Database = "BookLibrarySystem";
oBackup.Files = path + "\\BookLibrarySystem.bak"; ;
oBackup.BackupSetName = "BookLibrarySystem";
oBackup.BackupSetDescription = "数据库备份";
oBackup.Initialize = true;
oBackup.SQLBackup(oSQLServer);
ret = 1;
}
catch
{
ret = 0;
throw;
}
finally
{
oSQLServer.DisConnect();
}
return ret;
}
/// <summary>
/// 数据库恢复
/// </summary>
public static int DbRestore(string serverip, string username, string psw, string path)
{
int ret;
SQLDMO.Restore oRestore = new SQLDMO.RestoreClass();
SQLDMO.SQLServer oSQLServer = new SQLDMO.SQLServerClass();
try
{
exepro(serverip, username, psw);
oSQLServer.LoginSecure = false;
oSQLServer.Connect(serverip, username, psw);
oRestore.Action = SQLDMO.SQLDMO_RESTORE_TYPE.SQLDMORestore_Database;
oRestore.Database = "BookLibrarySystem";
oRestore.Files = path + "\\BookLibrarySystem.bak";
oRestore.FileNumber = 1;
oRestore.ReplaceDatabase = true;
oRestore.SQLRestore(oSQLServer);
ret = 1;
}
catch
{
ret = 0;
throw;
}
finally
{
oSQLServer.DisConnect();
}
return ret;
}
/**/
/// <summary>
/// 杀死当前库的所有进程
/// </summary>
/// <returns></returns>
private static bool exepro(string serverip, string username, string psw)
{
SqlConnection conn1 = new SqlConnection("server=" + serverip + ";uid=" + username + ";pwd=" + psw + ";database=master");
string cmdTxt = "use master;";
cmdTxt += " declare @sql nvarchar(500) declare @spid int set @sql='declare getspid cursor for ";
cmdTxt += " select spid from sysprocesses where dbid=db_id('''+@dbname+''')' exec (@sql) ";
cmdTxt += " open getspid fetch next from getspid into @spid while @@fetch_status <>-1 begin ";
cmdTxt += " exec('kill '+@spid) fetch next from getspid into @spid end close getspid deallocate getspid ";
//SqlCommand cmd = new SqlCommand("p_killspid", conn1);
SqlCommand cmd = new SqlCommand(cmdTxt, conn1);
cmd.Parameters.Add(new SqlParameter("@dbname", "BookLibrarySystem"));
cmd.CommandType = CommandType.Text;
try
{
conn1.Open();
SqlDataReader dr = cmd.ExecuteReader();
ArrayList list = new ArrayList();
while (dr.Read())
{
list.Add(dr.GetInt16(0));
}
dr.Close();
for (int i = 0; i < list.Count; i++)
{
cmd = new SqlCommand(string.Format("KILL {0}", list), conn1);
cmd.ExecuteNonQuery();
}
conn1.Close();
return true;
}
catch (Exception ex)
{
return false;
}
finally
{
conn1.Close();
}
}