1

可能重复:
无法获得独占访问权限,因为数据库正在使用中

我在项目中使用 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 异常终止。将数据库上下文更改为“主”。将数据库上下文更改为“DB1”。

4

2 回答 2

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);

备份

        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

于 2012-12-19T12:27:22.623 回答
0

在调用之前插入以下行SqlCommand

_conn.ChangeDatabase("master");
于 2012-12-19T12:26:47.257 回答