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 が異常終了しています。データベース コンテキストを「master」に変更しました。データベース コンテキストを「DB1」に変更しました。

4

2 に答える 2

2

サーバーに接続したら、SMOを使用することをお勧めします(マスターは必要ありません)。

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 に答える