我用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();
        }
    }
}

解决方案 »

  1.   

    Test,因为它正由此会话使用先把服务停止先
      

  2.   

    我用的时 Sql sever 2005 数据库
      

  3.   

    NET STOP MSSQLSERVER
    05的不知道
      

  4.   

    先终止与数据库连接的所有进程,用下面的存储过程,参数为数据库名称
    然后再还原就行了
    CREATE procedure killspid @dbname varchar(50)
    as
    begin
    declare @a int
    declare getid cursor for select spid from sysprocesses where dbid=db_id(@dbname)
    open getid
    fetch next from getid into @a
    while @@fetch_status<>-1
    begin
        exec('kill '+@a)
        fetch next from getid into @a
    end
    close getid
    deallocate getid
    end
    GO
      

  5.   

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

  6.   

    这个需要在master使用,才能停掉你的数据库,我做过测试!
    如果你在当前数据中使用,还是会有问题的!
      

  7.   

    谢谢大家的帮忙。问题已经解决。首先 use master;
    再 alter database dbname set offline with rollback immediate;
    再 备份任务日志;(SQL Server 2005 在恢复时必须备份当前任务日志)
    再 恢复数据库;
    再 alter database dbname set online with rollback immediate;
      

  8.   

    在sql语句后面加上with replace
    比如
    use master
    go
    restore database shaixuan from disk='E:\s\database\backup\backuptext.dat' with replace
    go
    这个在数据库上执行就没有错