c# - 如何以编程方式恢复备份

标签 c# sql-server winforms localdb

我通过单击按钮创建了备份

我的代码是

con.Open();

string str = "USE [C:\\Users\\asus\\Documents\\Visual Studio 2012\\Projects\\bbcon_accout_software\\bb_con_accnt_soft_lib\\BbCon.mdf]";
string str1 = "BACKUP DATABASE [C:\\Users\\asus\\Documents\\Visual Studio 2012\\Projects\\bbcon_accout_software\\bb_con_accnt_soft_lib\\BbCon.mdf] TO DISK = 'C:\\Users\\Public\\aa.Bak' WITH FORMAT,MEDIANAME = 'Z_SQLServerBackups',NAME = 'Full Backup of Testdb';";

SqlCommand cmd1 = new SqlCommand(str, con);
SqlCommand cmd2 = new SqlCommand(str1, con);

cmd1.ExecuteNonQuery();
cmd2.ExecuteNonQuery();

MessageBox.Show("success");
con.Close();

现在我想恢复备份的数据库,请帮助我搜索了很多问题,但我没有得到我需要的答案 - 请帮助我执行此任务。

我尝试使用此代码恢复:

string query = "RESTORE DATABASE BbCon FROM DISK='C:\\Users\\Public\\aa.Bak' WITH REPLACE";
con.Open();

using (SqlCommand cmd = new SqlCommand(query, con))
{
    cmd.ExecuteNonQuery();
}

con.Close();

但我收到错误

enter image description here

请帮我解决这个问题

最佳答案

每个物理文件都需要驻留在您尝试将备份数据库还原到的系统上的某个位置。错误消息告诉您这些文件正在被另一个数据库使用。您可以查询 sys.master_files 以找出它们属于哪个数据库。

要解决此问题,您需要删除正在使用这些物理文件的数据库,或者在 RESTORE 语句中添加 MOVE 子句。对于后者,它看起来像这样:

RESTORE DATABASE BbCon FROM DISK='C:\\Users\\Public\\aa.Bak' WITH REPLACE,
move 'BBCon' to 'c:\temp\BBCon.mdf',
move 'BBCon_log' to 'c:\temp\BBCon_log.ldf';

关于c# - 如何以编程方式恢复备份,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41794792/

相关文章:

sql-server - 如何在 SQL 中对单列连接的日期时间字段求和

c# - DateTimePicker 日历按钮宽度

c# - 在集成测试 Web API 时使用 TransactionScope

c# - 来自嵌入图像的 BitmapSource

c# - Razor 智能感知错误 : Feature 'extension method' cannot be used because it is not part of the ISO-2 C# language specification

sql - 如何在 Microsoft Sql Server 2012 中选择从 2002 年到 2013 年的所有日期

sql-server - 将 NULL 值传递到参数化 delphi SQL Server 查询中

c# - Windows 窗体 MSN Messenger 登录

c# - 不可调用成员

c# - 如何在wpf应用程序中设置所有窗口的背景图片