日期:2014-05-18  浏览次数:20577 次

急!!数据库备份恢复时出现“无法处理,因为正由此会话使用”该如何解决
我用c#语言进行数据库开发,数据库备份时一切正常,可是到数据库恢复时就出现问题,总是弹出“无法处理数据库Test,因为它正由此会话使用……”,问各位高手如果解决,急啊……………………

代码如下:

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;

public partial class _Default : System.Web.UI.Page 
{
  protected void Page_Load(object sender, EventArgs e)
  {

  }
  protected void Button1_Click(object sender, EventArgs e)
  {
  string path=@"c:\Test.bak";
  string backupstr="backup database Test to disk='"+path+"';";
  SqlConnection con = new SqlConnection("server=.;uid=sa;pwd=;");
  SqlCommand cmd = new SqlCommand(backupstr, con);
  try
  {
  con.Open();
  cmd.ExecuteNonQuery();
  this.Label1.Text = "备份成功!";

  }
  catch
  {
  this.Label1.Text = "备份失败!";
  }
  finally
  {
  con.Close();
  }
  }
  protected void Button2_Click(object sender, EventArgs e)
  {
  string path = @"c:\Test.bak";
  string restore="restore database Test from disk='"+path+"';";
  SqlConnection con=new SqlConnection("server=.;uid=sa;pwd=;");
  SqlCommand cmd=new SqlCommand(restore,con);
  try
  {
  con.Open();
  cmd.ExecuteNonQuery();
  this.Label1.Text = "恢复成功";

  }
  catch
  {
  this.Label1.Text = "恢复失败";
  }
  finally
  {
  con.Close();
  }
  }
}


------解决方案--------------------
先让数据库离线再执行还原操作,
alter database dbname set offline with rollback immediate;