我正在为一个应用程序编写一个简单的数据库备份和恢复程序。我可以毫无问题地备份我的数据库,但是当我恢复时,我无法获得对我的数据库的独家访问。
我尝试了所有修复SO的组合,把它放在单用户模式下,脱机后再放回去,都没有成功。 我可以在工作室管理器(Express)中成功恢复数据库。
这种方法是当时与SQL服务器的唯一连接,所以我不明白为什么我不能执行还原。
感谢帮助,指出问题可能出在哪里。
internal void RestoreDatabase(string databaseFile)
//get database details
var databaseConfiguration = new DatabaseConfiguration().GetDatabaseConfiguration();
//construct server connection string
var connection = databaseConfiguration.IsSqlAuthentication
? new ServerConnection(databaseConfiguration.ServerInstance,
databaseConfiguration.SqlUsername,
databaseConfiguration.SqlPassword)
: new ServerConnection(databaseConfiguration.ServerInstance);
//set database to single user and kick everyone off
using (
var sqlconnection =
new SqlConnection(new DatabaseConfiguration().MakeConnectionString(databaseConfiguration)))
sqlconnection.Open();
using (
var sqlcommand = new SqlCommand("ALTER DATABASE " + databaseConfiguration.DatabaseName + " SET Single_User WITH Rollback IMMEDIATE",
sqlconnection))
sqlcommand.ExecuteNonQuery();
using (
var sqlcommand = new SqlCommand("ALTER DATABASE " + databaseConfiguration.DatabaseName + " SET OFFLINE",
sqlconnection))
sqlcommand.ExecuteNonQuery();
using (
var sqlcommand = new SqlCommand("ALTER DATABASE " + databaseConfiguration.DatabaseName + " SET ONLINE",
sqlconnection))
sqlcommand.ExecuteNonQuery();
sqlconnection.Close();
//setup server connection and restore
var server = new Server(connection);
var restore = new Restore();
restore.Database = databaseConfiguration.DatabaseName;
restore.Action = RestoreActionType.Database;
restore.Devices.AddDevice(databaseFile, DeviceType.File);
restore.ReplaceDatabase = true;
restore.Complete += Restore_Complete;
restore.SqlRestore(server);
catch (Exception ex)
//my bad
restoreDatabaseServerError(ex.InnerException.Message, EventArgs.Empty);
finally
//set database to multi user
using (
var sqlconnection =
new SqlConnection(new DatabaseConfiguration().MakeConnectionString(databaseConfiguration)))
sqlconnection.Open();
using (
var sqlcommand = new SqlCommand("ALTER DATABASE " + databaseConfiguration.DatabaseName + " SET Multi_User",
sqlconnection))
sqlcommand.ExecuteNonQuery();
sqlcommand.Dispose();
sqlconnection.Close();