场景:
我正在使用SQL Server 2008 R2数据库服务器处理C#windows窗体应用程序。所有事情都进展顺利,即使我能够创建数据库备份,但是当我以编程方式恢复它时,它会给我错误“ RESTORE无法处理数据库'Test_DB',因为此会话正在使用它。建议在执行此操作时使用master数据库。 RESTORE DATABASE异常终止。“ 这是我的备份和恢复程序
// back up code
try
{
SaveFileDialog sd = new SaveFileDialog();
sd.Filter = "SQL Server database backup files|*.bak";
sd.Title = "Create Database Backup";
if (sd.ShowDialog() == DialogResult.OK)
{
using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["dbConnection"].ConnectionString))
{
string sqlStmt = string.Format("backup database Test_DB to disk='{0}'", sd.FileName);
using (SqlCommand bu2 = new SqlCommand(sqlStmt, conn))
{
conn.Open();
bu2.ExecuteNonQuery();
conn.Close();
DevComponents.DotNetBar.MessageBoxEx.Show("Backup Created Sucessfully");
}
}
}
}
catch (Exception)
{
MessageBox.Show("Backup Not Created");
}
// Restore backup Code
try
{
OpenFileDialog od = new OpenFileDialog();
od.Filter = "SQL Server database Restore files|*.bak";
od.Title = "Restore Database Backup";
if (od.ShowDialog() == DialogResult.OK)
{
using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["dbConnection"].ConnectionString))
{
string sqlStmt = string.Format("Restore database Test_DB from disk='{0}'", od.FileName);
using (SqlCommand bu2 = new SqlCommand(sqlStmt, conn))
{
conn.Open();
bu2.ExecuteNonQuery();
conn.Close();
DevComponents.DotNetBar.MessageBoxEx.Show("Database Retored Sucessfully", "Success Message!");
}
}
}
}
catch (Exception)
{
MessageBox.Show("Database didn't Restore","Error Message!");
}
我感谢任何机构提供的任何帮助。感谢。
答案 0 :(得分:5)
错误消息不言自明。您需要更改连接字符串,而不是initial catalog=test_db
,而是initial_catalog=master
。或者在运行还原之前将数据库上下文更改为master。
答案 1 :(得分:3)
// Restore backup Code
try
{
OpenFileDialog od = new OpenFileDialog();
od.Filter = "SQL Server database Restore files|*.bak";
od.Title = "Restore Database Backup";
if (od.ShowDialog() == DialogResult.OK)
{
using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["dbConnection"].ConnectionString))
{
conn.Open();
string UseMaster = "USE master";
SqlCommand UseMasterCommand = new SqlCommand(UseMaster, conn);
UseMasterCommand.ExecuteNonQuery();
string Alter1 = @"ALTER DATABASE [Test_DB] SET Single_User WITH Rollback Immediate";
SqlCommand Alter1Cmd = new SqlCommand(Alter1, conn);
Alter1Cmd.ExecuteNonQuery();
string Restore = string.Format("Restore database Test_DB from disk='{0}'", od.FileName);
SqlCommand RestoreCmd = new SqlCommand(Restore, conn);
RestoreCmd.ExecuteNonQuery();
string Alter2 = @"ALTER DATABASE [Test_DB] SET Multi_User";
SqlCommand Alter2Cmd = new SqlCommand(Alter2, conn);
Alter2Cmd.ExecuteNonQuery();
conn.Close();
DevComponents.DotNetBar.MessageBoxEx.Show("Database Retored Sucessfully", "Success Message!");
}
}
}
catch (Exception)
{
MessageBox.Show("Database didn't Restore", "Error Message!");
}