How to recover SQL Server 2012.bak database file in C #?

I developed MIS in Windows Forms, in which I backed up the SQL Server 2012 database, but I cannot restore the backup file ( .bak).

This is my code:

private void buttonRestore_Click(object sender, EventArgs e)
{
    try
    {
        openFileDialog1.Filter = "Backup File |*.bak";

        if (openFileDialog1.ShowDialog() == DialogResult.OK)
        {
            string sql = "Alter Database BOQ SET SINGLE_USER WITH ROLLBACK IMMEDIATE;";
            sql += "Restore Database BOQ FROM DISK ='" + openFileDialog1.FileName + "' WITH REPLACE;";

            SqlConnection con = new SqlConnection("Data Source=.; Initial Catalog=BOQ;Integrated Security=True");
            SqlCommand command = new SqlCommand(sql,con);

            con.Open();
            command.ExecuteNonQuery();

            MessageBox.Show("Database Recovered Successfully!");
            con.Close();
            con.Dispose();
        }
    }
    catch (Exception ex) 
    { 
         MessageBox.Show(ex.Message); 
    }
}

But I get this error:

enter image description here

+1
source share
1 answer

You cannot connect to your database BOQand then restore .bakon top of it!

"Data Source=.; Initial Catalog=BOQ;Integrated Security=True"
                                ****

You need to connect to the database masterand , then , you can restore the database BOQ:

"Data Source=.; Initial Catalog=master;Integrated Security=True"
                                *******
+5
source

Source: https://habr.com/ru/post/1612882/


All Articles