如何备份 - 恢复.mdf数据库

时间:2012-06-29 18:06:20

标签: c# sql-server visual-studio-2010 visual-studio sql-server-2008

我用vs2010和c#开发了一个Windows应用程序。我想知道一种以编程方式备份​​和恢复本地mdf数据库的方法。使用sdf数据库我使用文件复制,但它似乎不适用于mdf文件。 有人可以帮忙吗?

2 个答案:

答案 0 :(得分:2)

尝试这种方式:

  • 转到Sql Management Studio并选择所需的数据库 备份
  • 右键单击并选择“任务” - > '备份'
  • 根据需要调整参数,但不确认对话框
  • 按下SCRIPT按钮并关闭对话框
  • 在查询窗口中,在备份前插入以下文本 命令

    CREATE PROCEDURE DO_BACKUP  
    AS  
    BEGIN  
       -- HERE GOES THE BACKUP TEXT CREATED BY THE SCRIPT BUTTON   
       -- FOR EXAMPLE
       BACKUP DATABASE [Customers] 
       TO DISK = N'E:\backups\customers.bak' 
       WITH NOFORMAT, NOINIT,  
       NAME = N'Customers - Full Database Backup', 
       SKIP, NOREWIND, NOUNLOAD,  STATS = 10
    END  
    

并使用感叹号按钮执行(选择正确的数据库)。

现在您有一个名为DO_BACKUP的存储过程,您可以使用常规ADO.NET对象(例如SqlConnectionSqlCommand

从您的代码中调用它们

答案 1 :(得分:0)

我为此苦苦挣扎,接受的答案并不能解决问题,所以这里有一个对我有用的解决方案(感谢 dnxit

它可能对某人有所帮助。

备份

try
{
    var dlg = new System.Windows.Forms.FolderBrowserDialog();
    var result = dlg.ShowDialog(this.GetIWin32Window());

    if (result.ToString() == "OK")
    {
        var dbfileName = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "LibraryManger.mdf");
        var backupConn = new SqlConnection { ConnectionString = eb.GetConnectionString() };
        backupConn.Open();

        var backupcomm = backupConn.CreateCommand();
        var backupdb = $@"BACKUP DATABASE ""{dbfileName}"" TO DISK='{Path.Combine(dlg.SelectedPath,"LibraryManagement.bak")}'";
        var backupcreatecomm = new SqlCommand(backupdb, backupConn);
        backupcreatecomm.ExecuteNonQuery();
        backupConn.Close();

        MessageBox.Show($"Database backup has successfully stored in {Path.Combine(dlg.SelectedPath, "LibraryManagement.bak")}", "Confirmation");
    }
}
catch (Exception ex)
{
    if(ex.Message.Contains("Operating system error"))
    {
        MessageBox.Show("Please chose a public folder.", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
    }
    else
        MessageBox.Show(ex.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
}

恢复

您必须在恢复之前关闭现有连接

try
{
    if (eb != null)
    {
        eb.DisposeConnection();
        eb = null;
    }

    var dlg = new OpenFileDialog();
    dlg.InitialDirectory = "C:\\";
    dlg.Filter = "Database file (*.bak)|*.bak";
    dlg.RestoreDirectory = true;

    if (Equals(dlg.ShowDialog(), true))
    {
        using (var con = new SqlConnection())
        {
            con.ConnectionString = @"Data Source=(LocalDB)\MSSQLLocalDB;Database=Master;Integrated Security=True;Connect Timeout=30;";
            con.Open();
            var dbfileName = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "LibraryManger.mdf");
                using (var cmd = new SqlCommand())
                {
                    cmd.Connection = con;
                    cmd.CommandText = $@"RESTORE DATABASE ""{dbfileName}"" FROM DISK='{dlg.FileName}'";

                    cmd.ExecuteNonQuery();
                }
                con.Close();
            }

        MessageBox.Show($"Database backup has successfully restored.", "Confirmation");
        eb = new EntityBroker.EntityBroker();
    }
}
catch (Exception ex)
{
    MessageBox.Show(ex.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
}