user3304978
user3304978

Reputation: 1

RESTORE cannot process database

I design one application for backup and restore mechanism . When I press on the backup button it will successfully creates the backup file on the selected path. But when I want to restore the same database then that time it showing me an error

RESTORE cannot process database 'email_client' because it is in use bye this session. It is recommended that the master database be used when performing this operation.RESTORE DATABASE is terminating abnormally

so please provide coding for it

    private SqlCommand cmd;
    string sql = "";
    public Backup()
    {
        InitializeComponent();
    }

    private void button2_Click(object sender, EventArgs e)
    {
        SqlConnection con = new SqlConnection("Data Source=.;Initial Catalog=email_client;Integrated Security=True");
        con.Open();
        try
        {
            SqlCommand cmd = new SqlCommand("backup database email_client to disk ='" + textBox1.Text + "\\" + textBox2.Text + ".bak'", con);
            cmd.ExecuteNonQuery();
            MessageBox.Show("done");


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

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

    private void button4_Click(object sender, EventArgs e)
    {
        OpenFileDialog dlg = new OpenFileDialog();
        dlg.Filter = "Backup files(*.bak)|*.bak|All Files(*.*)|*.*";
        dlg.FilterIndex = 0;
        if (dlg.ShowDialog() == DialogResult.OK)
        {
            textBox3.Text = dlg.FileName;
        }

    }

    private void button3_Click(object sender, EventArgs e)
    {

        SqlConnection con = new SqlConnection("Data Source=.;Initial Catalog=email_client;Integrated Security=True");
        con.Open();
        try
        {

            sql = "alter database email_client set single_user with rollback immediate ;";
            sql += "RESTORE database email_client from disk='"+textBox3.Text+"'with replace;";
            cmd = new SqlCommand(sql, con);
            cmd.ExecuteNonQuery();
            con.Close();
            con.Dispose();
            MessageBox.Show("done");

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

    }


}

}

Upvotes: 0

Views: 1836

Answers (1)

jpw
jpw

Reputation: 44921

You need to change database context before running the restore so either change the connection string from Initial Catalog=email_client to initial_catalog=master or include a USE master; statement at the start of the SQL command to switch context.

Upvotes: 1

Related Questions