Backup and Restore Sql Server database in C#

This tutorial explains how to create a Sql Server Backup file in C# and also how to restore the

database. We use a Backup file and restore database when our database becomes

corrupted or crashes. So let's have a pratical example of  how to create it in C#, this example is

developed in Visual Studio 2010.

 First, we create this Windows Form and we declare the connectionString of the database.

Backup & Restore Sql Server database in C#

SqlConnection con = new SqlConnection(WindowsFormsApplication11.Properties.Settings.Default.database1ConnectionString);


We start by the Backup, in BrowseButton click event we add this code:

private void browseButton_Click(object sender, EventArgs e)
{
    FolderBrowserDialog dlg = new FolderBrowserDialog();
    if (dlg.ShowDialog() == DialogResult.OK)
    {
         textBox1.Text = dlg.SelectedPath;
         BackupButton.Enabled = true;
    }
}

In BackupButton click event we add this code:

private void BackupButton_Click(object sender, EventArgs e)
{
    string database = con.Database.ToString();
    try
    {
        if(textBox1.Text==string.Empty)
        {
            MessageBox.Show("please enter backup file location");
        }
        else
        {
            string cmd = "BACKUP DATABASE [" + database + "] TO DISK='" + textBox1.Text + "\\" + "database" + "-" + DateTime.Now.ToString("yyyy-MM-dd--HH-mm-ss") + ".bak'";

            using(SqlCommand command = new SqlCommand(cmd,con))
            {
                if(con.State!=ConnectionState.Open)
                {
                    con.Open();
                }
                command.ExecuteNonQuery();
                con.Close();
                MessageBox.Show("database backup done successefully");
                BackupButton.Enabled = false;
            }
       }

    }
    catch
    {

    }
}

Then, let's handle Restore database. In BrowseButton click event we add this code:

private void Browsebutton2_Click(object sender, EventArgs e)
{
    OpenFileDialog dlg = new OpenFileDialog();
    dlg.Filter = "SQL SERVER database backup files|*.bak";
    dlg.Title = "Database restore";
    if (dlg.ShowDialog() == DialogResult.OK)
    {
        textBox2.Text = dlg.FileName;
        restoreButton.Enabled = true;
    }
}

Finally, in RestoreButton click event we put this code:

private void restoreButton_Click(object sender, EventArgs e)
{
    string database = con.Database.ToString();
    if (con.State != ConnectionState.Open)
    {
        con.Open();
    }
    try
    {
        string sqlStmt2 = string.Format("ALTER DATABASE [" + database + "] SET SINGLE_USER WITH ROLLBACK IMMEDIATE");
        SqlCommand bu2 = new SqlCommand(sqlStmt2, con);
        bu2.ExecuteNonQuery();

        string sqlStmt3 = "USE MASTER RESTORE DATABASE [" + database + "] FROM DISK='" + textBox2.Text + "'WITH REPLACE;";
        SqlCommand bu3 = new SqlCommand(sqlStmt3, con);
        bu3.ExecuteNonQuery();

        string sqlStmt4 = string.Format("ALTER DATABASE [" + database + "] SET MULTI_USER");
        SqlCommand bu4 = new SqlCommand(sqlStmt4, con);
        bu4.ExecuteNonQuery();

        MessageBox.Show("database restoration done successefully");
        con.Close();

   }
   catch (Exception ex)
   {
        MessageBox.Show(ex.ToString());
   }
}

Fore more explanation, watch this video:




Backup and Restore Sql Server database in C# Backup and Restore Sql Server database in C# Reviewed by Bloggeur DZ on 11:58 Rating: 5

12 commentaires:

  1. en la cadena de conexion, la parte de database1ConnectionString a que hace referencia?? le e puesto el nombre de la base de datos y me marca error

    RépondreSupprimer
  2. "\\" + "database" + "-" what is this in code which location...this database word give error ..please help me

    RépondreSupprimer
  3. Great work bro. Complete yet precise. Keep it up the great work. Thanks!

    RépondreSupprimer
  4. how to take back up sql server data base with different Name Like DataBase_Restore and Restore with new Name

    RépondreSupprimer
  5. Thanks for sharing this useful article. Looking for a best Database Backup and Restore Services in usa. We provide this service for an affordable price. Database Backup and Restore Services in usa

    RépondreSupprimer
  6. Failed to update database "msdb" because the database is read-only.
    Could not insert a backup or restore history/detail record in the msdb database. This may indicate a problem with the msdb database. The backup/restore operation was still successful.

    RépondreSupprimer
  7. hii its helpfull but i am not able to backup same database witch is in the project....help me

    RépondreSupprimer
  8. Recovering the data base
    At Genex DBS data loss is only temporary and we prove it every day with the highest data recovery success rate in the industry. Our volume of recovered data speaks for itself.
    For over 17 years, Data Storage Solutions has performed professional data recovery on every kind of storage device including Desktop hard drive data recovery, Laptop hard drives data recovery, External / USB hard disc Data Recovery / Hard Disc Recovery, Server and RAID arrays data recovery, NAS, SAN, DAS, SSD, Encryption storage devices data recovery, Database & File Recovery, CCTV Data Recovery, Flash Card Data Recovery. and enterprise-level devices like RAIDs. We have proprietary tools to handle every kind of data loss situation on any server including physical and mechanical failure, backup failure, water and fire damage, data corruption, file deletion, head crash, system failure, and more. We conduct all our data recoveries using software and solutions that won’t further damage your device.Genexdbs Database

    RépondreSupprimer

Fourni par Blogger.