RESTORE无法处理数据库

时间:2014-02-22 17:04:48

标签: c# sql sql-server

我为备份和恢复机制设计了一个应用程序。当我按下备份按钮时,它将在所选路径上成功创建备份文件。但是,当我想恢复相同的数据库时,那时它会显示错误

  

RESTORE无法处理数据库'email_client',因为它正在使用中   再见本节。建议使用master数据库   执行此操作时.RESTORE DATABASE正在终止   异常

所以请提供编码

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

    }


}

}

1 个答案:

答案 0 :(得分:1)

您需要在运行还原之前更改数据库上下文,以便将连接字符串从Initial Catalog=email_client更改为initial_catalog=master,或者在SQL命令的开头包含USE master;语句以切换上下文