繁体   English   中英

如何使用C#使用新的数据库名称还原Sqlserver .bak文件

[英]How to Restore Sqlserver .bak file with New database name using c#

我试图创建数据库备份并将其还原到另一个数据库,备份正在工作,但还原失败,原因是在创建备份时它也创建了数据库名称,例如, USe Master创建数据库[Samplename]然后生成所有表数据,因此,当我尝试使用c#还原,它尝试创建新的数据库作为Samplename而不是我的New SampleDB,然后给出异常

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




             }

下面的代码经过了稍微修改,现在可以在我这里使用。

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

我已经在Asp.net应用程序中使用了此解决方案。 我的备份和还原目标是固定的。 刚刚使用的文件浏览控件来获取备份文件名。 使用此解决方案之前,只需添加一些dll即可 您可以从安装SQL Server的路径中获取这些dll。 我的SQL Server位于D:\\ Program Files(x86)\\ Microsoft SQL Server。 因此,我从D:\\ Program Files(x86)\\ Microsoft SQL Server \\ 110 \\ SDK \\ Assemblies获取dll

只要在您的项目解决方案参考中包含以下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;
                }
            }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM