恢复数据库异常终止。在C#中将数据库上下文更改为'master'

时间:2019-05-02 13:50:38

标签: c# ado.net sql-server-2008r2-express

我已经在SQL SERVER 2008 R2版上创建了数据库。在C#中,我编写了用于备份和还原的代码。代码在同一台PC和同一台服务器上正常工作。但这会在另一台具有相同服务器名称的PC上产生错误。错误是“还原数据库异常终止。将数据库上下文更改为C#中的'master'”是我的代码。

备份代码:-

 private void Home_FormClosing(object sender, FormClosingEventArgs e)
    {
        if (!Directory.Exists(@"D:\\DBBackup"))
        {
            Directory.CreateDirectory(@"D:\\DBBackup");
        }
        string database = con.Database.ToString();
       try
        {

        string cmd = "BACKUP DATABASE [" + database + "] TO DISK='d:\\DBBackup\\" + database + "-" + DateTime.Now.ToString("dd-MM-yyyy--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");

        }


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

恢复代码:-

private void button2_Click(object sender, EventArgs e)
    {
        //this.openFileDialog1.Filter = "*.bak";
        openFileDialog1.ShowDialog();
        string path = openFileDialog1.FileName;
        string database = con.Database.ToString();
        if (con.State != ConnectionState.Open)
        {
            con.Open();
        }
        try
        {
            string sqlStmt2 = string.Format("ALTER DATABASE [" + database + "] SET MULTI_USER WITH ROLLBACK IMMEDIATE");
            SqlCommand bu2 = new SqlCommand(sqlStmt2, con);
            bu2.ExecuteNonQuery();

            string sqlStmt3 = "USE MASTER RESTORE DATABASE [" + database + "] FROM DISK='" + path + "'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();
            SqlCommand cmd = new SqlCommand("update DBBK Set Details='" + path + "' where DBNAME='" + database + "' ", bkcon);
            bkcon.Open();
            cmd.ExecuteNonQuery();
            bkcon.Close();


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

0 个答案:

没有答案