Possible Duplicate:
Exclusive access could not be obtained because the database is in use
I use C#, .net4 and SQL Server 2008 R2 in project and use this code to restore a database:
_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();
The following error is displayed:
Exclusive access could not be obtained because the database is in use.
RESTORE DATABASE is terminating abnormally.
Changed database context to ‘master’.
Changed database context to ‘DB1’.
its better to use SMO (cause no need for master) once you are connected to the server you do whatever you want
BACKUP
References :
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