2014-02-22 30 views
0

我为备份和恢复机制设计了一个应用程序。当我按下备份按钮时,它将成功地在所选路径上创建备份文件。但是,当我要恢复同一个数据库,然后那个时候它显示我的错误RESTORE无法处理数据库

RESTORE不能处理数据库“email_client”,因为它是在使用 告别本次会议。建议主数据库执行此operation.RESTORE数据库时终止 正常使用

所以请提供编码它

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

您需要更改数据库在运行还原之前,请将连接字符串从Initial Catalog=email_client更改为initial_catalog=master,或者在SQL命令开始时将USE master;语句包含到s巫婆背景。