Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Server backup&restore

backup

string connectionString1 = (@"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|Database1.mdf;Database=Database1;Integrated Security=True; User Instance=True");
            SqlConnection cn = new SqlConnection(connectionString1);
            cn.Open();
            SqlCommand cmd = new SqlCommand();
            SqlDataReader reader;
            cmd.CommandText = @"BACKUP DATABASE Database1 TO DISK = 'C:\SRI2Works.bak'";

            cmd.CommandType = CommandType.Text;
            cmd.Connection = cn;
            reader = cmd.ExecuteReader();
            cn.Close();
            MessageBox.Show("Database Backup Successfull.");

restore

string connectionString1 = (@"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|Database1.mdf;Database=Database1;Integrated Security=True; User Instance=True");
            SqlConnection cn = new SqlConnection(connectionString1);
            cn.Open();

            SqlCommand cmd = new SqlCommand();
            SqlDataReader reader;
            cmd.CommandText = @"use master; RESTORE DATABASE Database1 FROM DISK = 'C:\SRI2Works.bak'";
            cmd.CommandText = "DBCC CHECKDB ('Database1')";
            cmd.CommandType = CommandType.Text;
            cmd.Connection = cn;
            reader = cmd.ExecuteReader();
            cn.Close();
            MessageBox.Show("Database Restored Successfull.");

This code runs successfully but doesn't make any changes.

like image 470
user2252491 Avatar asked Apr 06 '13 15:04

user2252491


1 Answers

Try this code in Restore database:

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

For more explanation check out this tutorial: Backup & Restore Sql Server database using C#

like image 200
user4340666 Avatar answered Oct 04 '22 11:10

user4340666