How to backup a SQL Server 2014 Express Localdb (.mdf) file programmatically

前端 未结 2 1293
一向
一向 2020-12-20 06:09

I have simple Windows application which uses SQL Server 2014 LocalDB (.mdf file).

And I want that whenever users click exit button, my application autom

相关标签:
2条回答
  • 2020-12-20 06:42

    I finally solved after many trial and analysis. For someone who is looking for solutions, I share mine as below.

    It seems there's fewer people are developing with MS SQL Localdb than other databases.

    The name of database doesn't have to include extension like .mdf and the equal sign= has to be together as DISK=

    string backupdb = string.Format(@"BACKUP DATABASE greendb_{0} TO DISK='c:\Green_Backup\greendb_{0}.bak'", personID);

    0 讨论(0)
  • 2020-12-20 06:48

    it may help someone.

    Backup

    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);
    }
    

    Restore

    You'll have to close existing connection before you restore

    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);
    }
    
    0 讨论(0)
提交回复
热议问题