2016-03-04 72 views
0

我有使用SQL Server 2014 LocalDB的簡單Windows應用程序(.mdf文件)。如何以編程方式備份​​SQL Server 2014 Express Localdb(.mdf)文件

我希望當用戶單擊退出按鈕時,我的應用程序會自動將其localdb文件(.mdf)備份到同一臺計算機上的另一個文件夾中。

我寫了下面簡單的代碼,但發生的SQLException語法錯誤:

語法錯誤near`'C:\ greendb_angelheart.mdf」

DATABASE ""{0}""語法似乎罰款)

我擔心通過使用正常的SqlConnection代碼連接到特定的localdb文件是否正確。

我簡單的代碼是:

private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e) 
{ 
    if (MessageBox.Show("Really want to exit? Thank you !", MessageBoxButton.YesNo, MessageBoxImage.Warning) == MessageBoxResult.No) 
    { 
      e.Cancel = true; 
    } 
    else 
    { 
      string backuppath_basic = @"c:\Green_Backup"; 

      if (!System.IO.Directory.Exists("backuppath_basic")) 
      { 
       System.IO.Directory.CreateDirectory(backuppath_basic); 
      } 

      var greendbfileName = System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), string.Format("greendb_{0}.mdf", personID)); 
      var copied_greendbfileName = string.Format(@"C:\greendb_{0}.mdf", personID); 

      string localConnectionString = string.Format(@"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename= " + Environment.GetEnvironmentVariable("APPDATA") + @"\greendb_{0}.mdf;Integrated Security=True;Connect Timeout=30;", personID); 

      SqlConnection backupConn = new SqlConnection(); 
      backupConn.ConnectionString = localConnectionString; 
      backupConn.Open(); 

      SqlCommand backupcomm = backupConn.CreateCommand(); 
      string backupdb = @"BACKUP DATABASE ""{0}"" TO DISK '{1}'"; 
      backupdb = string.Format(backupdb, greendbfileName, copied_greendbfileName); 

      SqlCommand backupcreatecomm = new SqlCommand(backupdb, backupConn); 
      backupcreatecomm.ExecuteNonQuery(); 

      backupConn.Close(); 

      Environment.Exit(0); 
     } 
    } 
+0

我認爲你不能複製MDF,NDF或LDF文件,而SQL Server服務之前關閉現有的連接運行。你是否嘗試將數據庫脫機並複製?或分離 - 複製 - 附加?或者你爲什麼不採取簡單的完整備份? –

+0

@YusifYusifov,感謝您的評論,當我嘗試在應用程序運行時簡單複製時,由於另一個進程正在使用該文件,導致進程無法訪問數據庫文件,導致IOException。這就是爲什麼我問這個問題..SQL語法錯誤似乎通常很容易,但我沒有得到正確的語法,即使我嘗試了像單引號,雙引號,沒有引用等許多情況...任何好主意,將不勝感激! –

回答

0

我許多試驗和分析後,終於解決了。對於正在尋找解決方案的人,我分享如下。

似乎用MS SQL Localdb開發的人比其他數據庫少。

數據庫的名稱不必包括擴展像.mdf和等號=必須一起作爲DISK =

串的backupdb =的String.Format(@「BACKUP DATABASE greendb_ {0} TO DISK ='c:\ Green_Backup \ greendb_ {0} .bak'「,personID);

0

它可以幫助某人。

備份

try 
{ 
    var dlg = new System.Windows.Forms.FolderBrowserDialog(); 
    var result = dlg.ShowDialog(this.GetIWin32Window()); 

    if (result.ToString() == "OK") 
    { 
     var dbfileName = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "LibraryManger.mdf"); 
     var backupConn = new SqlConnection { ConnectionString = eb.GetConnectionString() }; 
     backupConn.Open(); 

     var backupcomm = backupConn.CreateCommand(); 
     var backupdb = [email protected]"BACKUP DATABASE ""{dbfileName}"" TO DISK='{Path.Combine(dlg.SelectedPath,"LibraryManagement.bak")}'"; 
     var backupcreatecomm = new SqlCommand(backupdb, backupConn); 
     backupcreatecomm.ExecuteNonQuery(); 
     backupConn.Close(); 

     MessageBox.Show($"Database backup has successfully stored in {Path.Combine(dlg.SelectedPath, "LibraryManagement.bak")}", "Confirmation"); 
    } 
} 
catch (Exception ex) 
{ 
    if(ex.Message.Contains("Operating system error")) 
    { 
     MessageBox.Show("Please chose a public folder.", "Error", MessageBoxButton.OK, MessageBoxImage.Error); 
    } 
    else 
     MessageBox.Show(ex.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error); 
} 

恢復

你有你恢復

try 
{ 
    if (eb != null) 
    { 
     eb.DisposeConnection(); 
     eb = null; 
    } 

    var dlg = new OpenFileDialog(); 
    dlg.InitialDirectory = "C:\\"; 
    dlg.Filter = "Database file (*.bak)|*.bak"; 
    dlg.RestoreDirectory = true; 

    if (Equals(dlg.ShowDialog(), true)) 
    { 
     using (var con = new SqlConnection()) 
     { 
      con.ConnectionString = @"Data Source=(LocalDB)\MSSQLLocalDB;Database=Master;Integrated Security=True;Connect Timeout=30;"; 
      con.Open(); 
      var dbfileName = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "LibraryManger.mdf"); 
       using (var cmd = new SqlCommand()) 
       { 
        cmd.Connection = con; 
        cmd.CommandText = [email protected]"RESTORE DATABASE ""{dbfileName}"" FROM DISK='{dlg.FileName}'"; 

        cmd.ExecuteNonQuery(); 
       } 
       con.Close(); 
      } 

     MessageBox.Show($"Database backup has successfully restored.", "Confirmation"); 
     eb = new EntityBroker.EntityBroker(); 
    } 
} 
catch (Exception ex) 
{ 
    MessageBox.Show(ex.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error); 
} 
相關問題