How to backup Sql Database Programmatically in C#

后端 未结 10 1827
说谎
说谎 2020-12-23 11:48

I want to write a code to backup my Sql Server 2008 Database using C# in .Net 4 FrameWork. Can anyone help in this.

相关标签:
10条回答
  • 2020-12-23 12:03

    This worked for me...

    private void BackupButtonClick(object sender, RoutedEventArgs e)
    {
        // FILE NAME WITH DATE DISTICNTION
        string fileName = string.Format("SchoolBackup_{0}.bak", DateTime.Now.ToString("yyyy_MM_dd_h_mm_tt"));
        try
        {
            // YOUR SEREVER OR MACHINE NAME
            Server dbServer = new Server (new ServerConnection("DESKTOP"));
            Microsoft.SqlServer.Management.Smo.Backup dbBackup = new Microsoft.SqlServer.Management.Smo.Backup()
            {
                Action = BackupActionType.Database, 
                Database = "School"
            };
    
            dbBackup.Devices.AddDevice(@backupDirectory() +"\\"+ fileName, DeviceType.File);
            dbBackup.Initialize = true;
            dbBackup.SqlBackupAsync(dbServer);
    
    
            MessageBox.Show("Backup", "Backup Completed!");
        }
        catch(Exception err)
        {
            System.Windows.MessageBox.Show(err.ToString());
        }
    }
    
    
    // THE DIRECTOTRY YOU WANT TO SAVE IN
    public string backupDirectory()
    {
        using (var dialog = new FolderBrowserDialog())
        {
            var result = dialog.ShowDialog();
            return dialog.SelectedPath;
        }
    }
    
    0 讨论(0)
  • 2020-12-23 12:07
     private void BackupManager_Load(object sender, EventArgs e)
            {
                txtFileName.Text = "DB_Backup_" + DateTime.Now.ToString("dd-MMM-yy");
            }
    
            private void btnDBBackup_Click(object sender, EventArgs e)
            {
                if (!string.IsNullOrEmpty(txtFileName.Text.Trim()))
                {
                    BackUp();
                }
                else
                {
                    MessageBox.Show("Please Enter Backup File Name", "", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    txtFileName.Focus();
                    return;
                }
            }
    
            private void BackUp()
            {
                try
                {
    
                    progressBar1.Value = 0;
    
                    for (progressBar1.Value = 0; progressBar1.Value < 100; progressBar1.Value++)
                    {
    
                    }
    
                    pl.DbName = "Inventry";
                    pl.Path = @"D:/" + txtFileName.Text.Trim() + ".bak";
    
                    for (progressBar1.Value = 100; progressBar1.Value < 200; progressBar1.Value++)
                    {
    
                    }
    
                    bl.DbBackUp(pl);
                    for (progressBar1.Value = 200; progressBar1.Value < 300; progressBar1.Value++)
                    {
    
                    }
    
                    for (progressBar1.Value = 300; progressBar1.Value < 400; progressBar1.Value++)
                    {
    
                    }
    
                    for (progressBar1.Value = 400; progressBar1.Value < progressBar1.Maximum; progressBar1.Value++)
                    {
    
                    }
                    if (progressBar1.Value == progressBar1.Maximum)
                    {
                        MessageBox.Show("Backup Saved Successfully...!!!", "", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                    else
                    {
                        MessageBox.Show("Action Failed, Please try again later", "", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
    
                catch (Exception ex)
                {
                    MessageBox.Show("Action Failed, Please try again later", "", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                finally
                {
                    progressBar1.Value = 0;
                }
            }
    
    0 讨论(0)
  • 2020-12-23 12:10

    You can use the following queries to Backup and Restore, you must change the path for your backup

    Database name=[data]

    Backup:

    BACKUP DATABASE [data] TO  DISK = N'C:\Program Files\Microsoft SQL Server\MSSQL10_50.MSSQLSERVER\MSSQL\Backup\data.bak' WITH NOFORMAT, NOINIT,  NAME = N'data-Full Database Backup', SKIP, NOREWIND, NOUNLOAD,  STATS = 10
    GO
    

    Restore:

    RESTORE DATABASE [data] FROM  DISK = N'C:\Program Files\Microsoft SQL Server\MSSQL10_50.MSSQLSERVER\MSSQL\Backup\data.bak' WITH  FILE = 1,  NOUNLOAD,  REPLACE,  STATS = 10
    GO
    
    0 讨论(0)
  • 2020-12-23 12:13

    you can connect to the database using SqlConnection and SqlCommand and execute the following command text for example:

    BACKUP DATABASE [MyDatabase] TO  DISK = 'C:\....\MyDatabase.bak'
    

    See here for examples.

    0 讨论(0)
  • 2020-12-23 12:14

    The following Link has explained complete details about how to back sql server 2008 database using c#

    Sql Database backup can be done using many way. You can either use Sql Commands like in the other answer or have create your own class to backup data.

    But these are different mode of backup.

    1. Full Database Backup
    2. Differential Database Backup
    3. Transaction Log Backup
    4. Backup with Compression

    But the disadvantage with this method is that it needs your sql management studio to be installed on your client system.

    0 讨论(0)
  • 2020-12-23 12:17

    It's a good practice to use a config file like this:

    <?xml version="1.0" encoding="utf-8"?>
    <configuration>
      <connectionStrings>
        <add name="MyConnString" connectionString="Data Source=(local);Initial Catalog=MyDB; Integrated Security=SSPI" ;Timeout=30"/>
      </connectionStrings>
      <appSettings>
        <add key="BackupFolder" value="C:/temp/"/>
      </appSettings>
    </configuration> 
    

    Your C# code will be something like this:

    // read connectionstring from config file
    var connectionString = ConfigurationManager.ConnectionStrings["MyConnString"].ConnectionString; 
    
    // read backup folder from config file ("C:/temp/")
    var backupFolder = ConfigurationManager.AppSettings["BackupFolder"];
    
    var sqlConStrBuilder = new SqlConnectionStringBuilder(connectionString);
    
    // set backupfilename (you will get something like: "C:/temp/MyDatabase-2013-12-07.bak")
    var backupFileName = String.Format("{0}{1}-{2}.bak", 
        backupFolder, sqlConStrBuilder.InitialCatalog, 
        DateTime.Now.ToString("yyyy-MM-dd"));
    
    using (var connection = new SqlConnection(sqlConStrBuilder.ConnectionString))
    {
        var query = String.Format("BACKUP DATABASE {0} TO DISK='{1}'", 
            sqlConStrBuilder.InitialCatalog, backupFileName);
    
        using (var command = new SqlCommand(query, connection))
        {
            connection.Open();
            command.ExecuteNonQuery();
        }
    }
    
    0 讨论(0)
提交回复
热议问题