如何恢复 SQL Server 2012 数据库?
How to restore SQL Server 2012 database?
如何从 SQL Server 2012 恢复数据库?
这是我的代码:
private void [connTes()][1]
{
try
{
conString = "server=.\SQLEXPRESS;database=db_datatestproject;user=admin;password=123;Integrated Security=True";
connnn = new SqlConnection(conString);
connnn.Open();
}
catch
{
}
}
private void button1_Click(object sender, EventArgs e)
{
connTes();
try
{
if (txtlocation.Text == "")
{
MessageBox.Show("select database");
return;
}
else
{
string databesing = connnn.Database.ToString();
string a = "ALTER DATABASE " + databesing + " SET SINGLE_USER WITH ROLLBACK IMMEDIATE;";
a += "RESTORE DATABASE "+databesing+" FROM DISK ='"+txtlocation.Text+"' WITH REPLACE;";
SqlCommand cmd = new SqlCommand(a, connnn);
SqlDataReader dr = cmd.ExecuteReader();
connnn.Close();
connnn.Dispose();
MessageBox.Show("done restored");
}
}
catch(SqlException ex)
{
MessageBox.Show(ex.ToString());
}
}
这是我得到的错误:
RESTORE cannot process database 'db_testproject' because it use by the session. It is recommended that the master database be used when performing this operation. RESTORE DATABASE is terminating abnormally.
如何解决这个错误?
非常感谢任何帮助。
谢谢。
添加
USE MASTER;
GO
到您的 TSQL 恢复命令的开头。
您需要在另一个数据库中,而不是您正在恢复的数据库中。
另请注意@marc_s的评论:"Since you're not getting back any data from that SqlCommand
, use ExecuteNonQuery()
instead of ExecuteReader()
"
如何从 SQL Server 2012 恢复数据库?
这是我的代码:
private void [connTes()][1]
{
try
{
conString = "server=.\SQLEXPRESS;database=db_datatestproject;user=admin;password=123;Integrated Security=True";
connnn = new SqlConnection(conString);
connnn.Open();
}
catch
{
}
}
private void button1_Click(object sender, EventArgs e)
{
connTes();
try
{
if (txtlocation.Text == "")
{
MessageBox.Show("select database");
return;
}
else
{
string databesing = connnn.Database.ToString();
string a = "ALTER DATABASE " + databesing + " SET SINGLE_USER WITH ROLLBACK IMMEDIATE;";
a += "RESTORE DATABASE "+databesing+" FROM DISK ='"+txtlocation.Text+"' WITH REPLACE;";
SqlCommand cmd = new SqlCommand(a, connnn);
SqlDataReader dr = cmd.ExecuteReader();
connnn.Close();
connnn.Dispose();
MessageBox.Show("done restored");
}
}
catch(SqlException ex)
{
MessageBox.Show(ex.ToString());
}
}
这是我得到的错误:
RESTORE cannot process database 'db_testproject' because it use by the session. It is recommended that the master database be used when performing this operation. RESTORE DATABASE is terminating abnormally.
如何解决这个错误?
非常感谢任何帮助。
谢谢。
添加
USE MASTER;
GO
到您的 TSQL 恢复命令的开头。
您需要在另一个数据库中,而不是您正在恢复的数据库中。
另请注意@marc_s的评论:"Since you're not getting back any data from that SqlCommand
, use ExecuteNonQuery()
instead of ExecuteReader()
"