2015-07-21 34 views
0

我試圖創建數據庫備份並恢復到另一個數據庫,備份正在工作但恢復失敗,原因是我在創建備份時創建的數據庫名稱也像 使用主 創建數據庫[Samplename] 然後生成所有表數據 所以,當我嘗試使用C#來恢復,它試圖創建新的數據庫爲Samplename沒有我的新SAMPLEDB,那麼它給例外如何用新的數據庫名稱恢復Sqlserver .bak文件使用c#

The file 'C:\Program Files (x86)\Microsoft SQL  
    Server\MSSQL11.BIZSQL\MSSQL\DATA\Product Company.mdf' cannot be 
overwritten. It is being used by database 'Sample Product Company'. 
    File 'Sample Product Company' cannot be restored to 'C:\Program Files 
(x86)\Microsoft SQL Server\MSSQL11.BIZSQL\MSSQL\DATA\Sample Product 
Company.mdf'. Use WITH MOVE to identify a valid location for the file. 

The file 'C:\Program Files (x86)\Microsoft SQL 
Server\MSSQL11.BIZSQL\MSSQL\DATA\Sample Product Company_log.ldf' cannot be overwritten. 
It is being used by database 'Sample Product Company'. 

File 'Sample Product Company_log' cannot be restored to 'C:\Program Files 
(x86)\Microsoft SQL Server\MSSQL11.BIZSQL\MSSQL\DATA\Sample Product 
Company_log.ldf'. Use WITH MOVE to identify a valid location for the file. 

Problems were identified while planning for the RESTORE statement. Previous  
messages provide details. 

    RESTORE DATABASE is terminating abnormally. 

你可以請指導我如何恢復與新數據庫的數據庫中SQlser2012R2

示例代碼還原:

 using (SqlConnection con = new SqlConnection(ConnectionString)) 
      { 
       con.Open(); 

       string UseMaster = "USE master"; 
       SqlCommand UseMasterCommand = new SqlCommand(UseMaster, con); 
       UseMasterCommand.ExecuteNonQuery(); 
       int iReturn = 0; 

       // If the database does not exist then create it. 
       string strCommand = string.Format("SET NOCOUNT OFF; SELECT COUNT(*) FROM master.dbo.sysdatabases where name=\'{0}\'", DatabaseName); 
       using (SqlCommand sqlCmd = new SqlCommand(strCommand, con)) 
       { 
        iReturn = Convert.ToInt32(sqlCmd.ExecuteScalar()); 
       } 
       if (iReturn == 0) 
       { 
        SqlCommand command = con.CreateCommand(); 
        command.CommandText = "CREATE DATABASE " + DatabaseName; 
        command.ExecuteNonQuery(); 
       } 
       ServerConnection serverConnection = new ServerConnection(con); 
       Microsoft.SqlServer.Management.Smo.Server srv = new Microsoft.SqlServer.Management.Smo.Server(serverConnection); 
       string Alter1 = @"ALTER DATABASE [" + DatabaseName + "] SET Single_User WITH Rollback Immediate"; 
       SqlCommand Alter1Cmd = new SqlCommand(Alter1, con); 
       Alter1Cmd.ExecuteNonQuery(); 
       string Restore = @"RESTORE Database [" + DatabaseName + "] FROM DISK = N'" + fileName + @"' WITH FILE = 1, NOUNLOAD, REPLACE, STATS = 10"; 
       SqlCommand RestoreCmd = new SqlCommand(Restore, con); 
       RestoreCmd.ExecuteNonQuery(); 
       string Alter2 = @"ALTER DATABASE [" + DatabaseName + "] SET Multi_User"; 
       SqlCommand Alter2Cmd = new SqlCommand(Alter2, con); 
       Alter2Cmd.ExecuteNonQuery(); 




      } 
+0

我測試了你的代碼,我沒有收到任何異常,恢復成功。當你調試時,你對變量「fileName」有什麼價值 – StackTrace

+0

文件名是:RestoreBackup。我在另一臺機器上創建備份並嘗試在我的系統中恢復,然後它的工作正常,但是如果我在我的機器上創建和恢復它不工作..我的機器有Windows8.1和Sqlserver2012 R2和另一臺機器有Windows7和Sqlserver2012R2 ..「 –

回答

0

稍微修改代碼的版本如下工作形成了我。

  string connectionString = ConfigurationManager.ConnectionStrings["TESTConnectionString"].ConnectionString; 
      using (SqlConnection con = new SqlConnection(connectionString)) 
      { 
       con.Open(); 

       string DatabaseName = "TEST"; 
       string fileName = "TEST.bak"; 

       string UseMaster = "USE master"; 
       SqlCommand UseMasterCommand = new SqlCommand(UseMaster, con); 
       UseMasterCommand.ExecuteNonQuery(); 
       int iReturn = 0; 

       // If the database does not exist then create it. 
       string strCommand = string.Format("SET NOCOUNT OFF; SELECT COUNT(*) FROM master.dbo.sysdatabases where name=\'{0}\'", DatabaseName); 
       using (SqlCommand sqlCmd = new SqlCommand(strCommand, con)) 
       { 
        iReturn = Convert.ToInt32(sqlCmd.ExecuteScalar()); 
       } 
       if (iReturn == 0) 
       { 
        SqlCommand command = con.CreateCommand(); 
        command.CommandText = "CREATE DATABASE " + DatabaseName; 
        command.ExecuteNonQuery(); 
       } 
       ServerConnection serverConnection = new ServerConnection(con); 
       Microsoft.SqlServer.Management.Smo.Server srv = new Microsoft.SqlServer.Management.Smo.Server(serverConnection); 
       string Alter1 = @"ALTER DATABASE [" + DatabaseName + "] SET Single_User WITH Rollback Immediate"; 
       SqlCommand Alter1Cmd = new SqlCommand(Alter1, con); 
       Alter1Cmd.ExecuteNonQuery(); 
       string Restore = @"RESTORE Database [" + DatabaseName + "] FROM DISK = N'" + fileName + @"' WITH FILE = 1, NOUNLOAD, REPLACE, STATS = 10"; 
       SqlCommand RestoreCmd = new SqlCommand(Restore, con); 
       RestoreCmd.ExecuteNonQuery(); 
       string Alter2 = @"ALTER DATABASE [" + DatabaseName + "] SET Multi_User"; 
       SqlCommand Alter2Cmd = new SqlCommand(Alter2, con); 
       Alter2Cmd.ExecuteNonQuery(); 
      } 
+1

」在我的機器上工作「幾乎沒有任何幫助OP ..你可以指出你所做的改變,以便人們不必手動比較OPs代碼和你的代碼。 – Default

+0

我比較你的代碼,所不同的只是你聲明的字符串(字符串數據庫名=「TEST」; 字符串文件名=「TEST.bak」;)保持,因爲它是...? –

+0

我試過手動恢復數據庫到另一個數據庫,即使它不恢復,它'創建相同的數據庫(我創建備份),我認爲當創建備份創建數據庫命令也添加,所以它試圖創建爲新的,而不是恢復..你有任何想法如何解決這個.. –

0

我在Asp.net應用程序中使用了這個解決方案。我的備份&恢復目標已修復。只需使用File Browse控件即可獲取備份文件的名稱。在使用此解決方案之前,只需添加一些dll。您可以從安裝SQL Server的路徑中獲取這些dll。我的SQL Server位於D:\ Program Files(x86)\ Microsoft SQL Server。所以我得到d的dll:\程序文件(x86)\ Microsoft SQL Server的\ 110個\ SDK \組件。

就包括到您的項目解決方案參考以下DLL文件。

我的SQL Server是2008 R2和2012 R2。在這兩種情況下,該解決方案都可以正常工作

using Microsoft.SqlServer.Management; 
using Microsoft.SqlServer.Management.Smo; 
using Microsoft.SqlServer.Management.Smo.Agent; 
using Microsoft.SqlServer.Management.Smo.Broker; 
using Microsoft.SqlServer.Management.Smo.Mail; 
using Microsoft.SqlServer.Management.Smo.RegisteredServers; 
using Microsoft.SqlServer.Management.Sdk.Sfc; 
using Microsoft.SqlServer.Management.Common; 



protected void btnDatabaseRestore_Click(object sender, EventArgs e) 
      { 
       try 
       { 

        string fileName = fileBrowsingForBackup.FileName; // Browse The Backup File From Device     

        string restorePath = string.Empty, userName = string.Empty, password = string.Empty, serverName = string.Empty, databaseName = string.Empty; 
        string backFileName = string.Empty, dataFilePath = string.Empty, logFilePath = string.Empty; 

        databaseName = "innboard20151215020030";// For Example Restore File Name innboard20151215020030.bak 

        restorePath = Server.MapPath(@"~/DatabaseBackup/"); // I used the folder for Restore The Database 

        dataFilePath = restorePath; 
        logFilePath = restorePath; 
        restorePath += databaseName + ".bak"; // Get the Backup File Path 

        databaseName = "innboard20151215020031"; // I want to Restore The Database name as "innboard20151215020031" 

//Get The Database Server Name, UserId, Passsword 

        string encryptedConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["InnboardConnectionString"].ConnectionString; 
        string decryptedConnectionString = Cryptography.Decrypt(encryptedConnectionString); 

        string[] wordConnectionString = decryptedConnectionString.Split(';'); 

        string mInitialCatalog = wordConnectionString[0]; 
        string mDataSource = wordConnectionString[1]; 
        string mUserId = wordConnectionString[2]; 
        string mPassword = wordConnectionString[3]; 

        string mInitialCatalogValue = mInitialCatalog.Split('=')[1]; 
        string mDataSourceValue = mDataSource.Split('=')[1]; 
        string mUserIdValue = mUserId.Split('=')[1]; 
        string mPasswordValue = mPassword.Split('=')[1]; 

        userName = mUserIdValue; 
        password = mPasswordValue; 
        serverName = mDataSourceValue; 

        // Call The Database Restore Method 
        RestoreDatabase(databaseName, restorePath, serverName, userName, password, dataFilePath, logFilePath); 

        CommonHelper.AlertInfo(innboardMessage, "Restore Database Succeed.", "success"); 
       } 
       catch (Exception ex) 
       { 
        CommonHelper.AlertInfo(innboardMessage, ex.InnerException.ToString(), "error"); 
       } 
      } 

// Database Restore Method 

    public void RestoreDatabase(String databaseName, String filePath, String serverName, String userName, String password, String dataFilePath, String logFilePath) 
      { 
       try 
       { 
//Action Type 
        Restore sqlRestore = new Restore(); 

        BackupDeviceItem deviceItem = new BackupDeviceItem(filePath, DeviceType.File); 
        sqlRestore.Devices.Add(deviceItem); 
        sqlRestore.Database = databaseName; 

        ServerConnection connection = new ServerConnection(serverName, userName, password); 
        Server sqlServer = new Server(connection); 

        Database db = sqlServer.Databases[databaseName]; 
        sqlRestore.Action = RestoreActionType.Database; 

//Create The Restore Database Ldf & Mdf file name 
        String dataFileLocation = dataFilePath + databaseName + ".mdf"; 
        String logFileLocation = logFilePath + databaseName + "_Log.ldf"; 
        db = sqlServer.Databases[databaseName]; 
        RelocateFile rf = new RelocateFile(databaseName, dataFileLocation); 

// Replace ldf, mdf file name of selected Backup file (in that case innboard20151215020030.bak) 
        System.Data.DataTable logicalRestoreFiles = sqlRestore.ReadFileList(sqlServer); 
        sqlRestore.RelocateFiles.Add(new RelocateFile(logicalRestoreFiles.Rows[0][0].ToString(), dataFileLocation)); 
        sqlRestore.RelocateFiles.Add(new RelocateFile(logicalRestoreFiles.Rows[1][0].ToString(), logFileLocation)); 

        sqlRestore.ReplaceDatabase = true; 

        sqlRestore.SqlRestore(sqlServer); 
        db = sqlServer.Databases[databaseName]; 
        db.SetOnline(); 
        sqlServer.Refresh(); 
       } 
       catch (Exception ex) 
       { 
        throw; 
       } 
      } 
相關問題