C#中的数据库恢复错误

时间:2012-12-19 12:11:43

标签: c# sql-server-2008-r2

  

可能重复:
  Exclusive access could not be obtained because the database is in use

我在项目中使用C#,。net4和SQL Server 2008 R2并使用此代码来恢复数据库:

_comm = new SqlCommand("use master; RESTORE DATABASE [DB1] FROM  DISK = @Address WITH  RESTRICTED_USER,  FILE = 1,  NOUNLOAD,  REPLACE,  STATS = 10; use DB1;", _conn);
        _comm.CommandType = System.Data.CommandType.Text;
        _comm.Parameters.AddRange(new SqlParameter[] 
                {
                new SqlParameter("@Address", _path)
                });

            _conn.Open();
            _comm.ExecuteNonQuery();

显示以下错误:

  

由于数据库正在使用,无法获得独占访问权限。    RESTORE DATABASE异常终止。    将数据库上下文更改为“master”。    将数据库上下文更改为“DB1”。

2 个答案:

答案 0 :(得分:2)

一旦你连接到服务器就可以更好地使用SMO(因为不需要master)

using Microsoft.SqlServer.Management.Smo;

...

        Server myServer = new Server(@".\SQLExpress");

        Database mydb = myServer.Databases["DB1"];
        if(mydb!=null)
           myServer.KillAllProcesses(mydb.Name);//detach

        Restore restoreDB = new Restore();
        restoreDB.Database = mydb.Name;

        restoreDB.Action = RestoreActionType.Database;
        restoreDB.Devices.AddDevice(_path, DeviceType.File);


        restoreDB.ReplaceDatabase = true;

        restoreDB.NoRecovery = false;

        restoreDB.SqlRestore(myServer);

<强> BACKUP

        Server myServer = new Server(@".\SQLExpress");

        Database mydb = myServer.Databases["DB1"];

        Backup bkp = new Backup();

        bkp.Action = BackupActionType.Database;

        bkp.Database = mydb.Name;

        bkp.Devices.AddDevice(_path, DeviceType.File);

        bkp.BackupSetName = "DB1 backup";//optional
        bkp.BackupSetDescription = "mybackup dated " + DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss");//optional

        bkp.Initialize = true;
        bkp.Incremental = false;

        bkp.SqlBackup(myServer);

参考文献:

C:\ Program Files(x86)\ Microsoft SQL Server \ 100 \ SDK \ Assemblies \ Microsoft.SqlServer.ConnectionInfo.dll

C:\ Program Files(x86)\ Microsoft SQL Server \ 100 \ SDK \ Assemblies \ Microsoft.SqlServer.Management.Sdk.Sfc.dll

C:\ Program Files(x86)\ Microsoft SQL Server \ 100 \ SDK \ Assemblies \ Microsoft.SqlServer.Smo.dll

C:\ Program Files(x86)\ Microsoft SQL Server \ 100 \ SDK \ Assemblies \ Microsoft.SqlServer.SmoExtended.dll

答案 1 :(得分:0)

在调用SqlCommand

之前插入以下行
_conn.ChangeDatabase("master");