2014-02-22 29 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巫婆背景。