Khuram Jan

Khuram Jan

  • NA
  • 5
  • 1.6k

Error in Restoring Database from Sql Server 200 using c#

Jul 23 2010 12:15 AM

I used two buttons for backup and Restore Database
        private void Restore_Click(object sender, EventArgs e)
        {
            con = new SqlConnection("Data Source = localhost; Initial                         Catalog=master ;Integrated Security = True;");
            con.Open();
            if (con.State == ConnectionState.Closed)
                con.Open();
            string qry = "Restore  database Peshawar_Children_Academy_Database from Disk= 'F:\\My.bak'";
            com = new SqlCommand("use master", con);
            com.ExecuteNonQuery();
            com = new SqlCommand(qry, con);
            com.ExecuteNonQuery();
            con.Close();
            MessageBox.Show("Has been restored database", "Restoration", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }
        private void Backup_Click(object sender, EventArgs e)
        {
            con = new SqlConnection("Data Source=localhost;Initial Catalog=Peshawar_Children_Academy_DataBase;Integrated Security = True;");
            con.Open();
            string qry = "backup database Peshawar_Children_Academy_Database to disk ='F:\\My.bak' with init,stats=10";
            com = new SqlCommand(qry, con);
            com.ExecuteNonQuery();
           
            con.Close();
            con.Dispose();
            MessageBox.Show("The support of the database was successfully performed", "Back", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }
If i click 1st Restore button then every thing goes ok. But if i click ist backup button to take bakup of database and then click on Restore button then i got the following error message
 Kindly help me as soon as possible
Message:
Exclusive access could not be obtained because the database is in use.
RESTORE DATABASE is terminating abnormally.

Answers (3)