【问题标题】:How to backup Sql Database Programmatically in C#如何在 C# 中以编程方式备份​​ Sql 数据库
【发布时间】:2012-03-23 07:34:47
【问题描述】:

我想在 .Net 4 FrameWork 中使用 C# 编写代码来备份我的 Sql Server 2008 数据库。任何人都可以在这方面提供帮助。

【问题讨论】:

    标签: .net database sql-server-2008 c#-4.0 backup


    【解决方案1】:

    您可以使用 SqlConnection 和 SqlCommand 连接到数据库并执行以下命令文本,例如:

    BACKUP DATABASE [MyDatabase] TO  DISK = 'C:\....\MyDatabase.bak'
    

    有关示例,请参阅 here

    【讨论】:

      【解决方案2】:

      最好使用这样的配置文件:

      <?xml version="1.0" encoding="utf-8"?>
      <configuration>
        <connectionStrings>
          <add name="MyConnString" connectionString="Data Source=(local);Initial Catalog=MyDB; Integrated Security=SSPI" ;Timeout=30"/>
        </connectionStrings>
        <appSettings>
          <add key="BackupFolder" value="C:/temp/"/>
        </appSettings>
      </configuration> 
      

      您的 C# 代码将如下所示:

      // read connectionstring from config file
      var connectionString = ConfigurationManager.ConnectionStrings["MyConnString"].ConnectionString; 
      
      // read backup folder from config file ("C:/temp/")
      var backupFolder = ConfigurationManager.AppSettings["BackupFolder"];
      
      var sqlConStrBuilder = new SqlConnectionStringBuilder(connectionString);
      
      // set backupfilename (you will get something like: "C:/temp/MyDatabase-2013-12-07.bak")
      var backupFileName = String.Format("{0}{1}-{2}.bak", 
          backupFolder, sqlConStrBuilder.InitialCatalog, 
          DateTime.Now.ToString("yyyy-MM-dd"));
      
      using (var connection = new SqlConnection(sqlConStrBuilder.ConnectionString))
      {
          var query = String.Format("BACKUP DATABASE {0} TO DISK='{1}'", 
              sqlConStrBuilder.InitialCatalog, backupFileName);
      
          using (var command = new SqlCommand(query, connection))
          {
              connection.Open();
              command.ExecuteNonQuery();
          }
      }
      

      【讨论】:

      • 我这里可能是错的,但这是否意味着 C# 程序必须与数据库在同一台服务器上运行?
      • @Eric Wu - 配置文件中的连接字符串可以指向任何 SQL 服务器,不必在同一台机器上。
      • 是的。我认为它是在应用程序级别以某种方式操作文件。似乎 backupfolder 指的是数据库服务器中的路径。
      • 如何在此处关闭备份文件。如果我在压缩后尝试删除 .bak 文件,它会显示“文件正在被另一个进程使用”...
      • @EricWu - bak 文件将在 sql-server 上生成,而不是代码运行的地方,如果这就是你的意思......
      【解决方案3】:

      为我工作:

      public class BackupService
      {
          private readonly string _connectionString;
          private readonly string _backupFolderFullPath;
          private readonly string[] _systemDatabaseNames = { "master", "tempdb", "model", "msdb" };
      
          public BackupService(string connectionString, string backupFolderFullPath)
          {
              _connectionString = connectionString;
              _backupFolderFullPath = backupFolderFullPath;
          }
      
          public void BackupAllUserDatabases()
          {
              foreach (string databaseName in GetAllUserDatabases())
              {
                  BackupDatabase(databaseName);
              }
          }
      
          public void BackupDatabase(string databaseName)
          {
              string filePath = BuildBackupPathWithFilename(databaseName);
      
              using (var connection = new SqlConnection(_connectionString))
              {
                  var query = String.Format("BACKUP DATABASE [{0}] TO DISK='{1}'", databaseName, filePath);
      
                  using (var command = new SqlCommand(query, connection))
                  {
                      connection.Open();
                      command.ExecuteNonQuery();
                  }
              }
          }
      
          private IEnumerable<string> GetAllUserDatabases()
          {
              var databases = new List<String>();
      
              DataTable databasesTable;
      
              using (var connection = new SqlConnection(_connectionString))
              {
                  connection.Open();
      
                  databasesTable = connection.GetSchema("Databases");
      
                  connection.Close();
              }
      
              foreach (DataRow row in databasesTable.Rows)
              {
                  string databaseName = row["database_name"].ToString();
      
                  if (_systemDatabaseNames.Contains(databaseName))
                      continue;
      
                  databases.Add(databaseName);
              }
      
              return databases;
          }
      
          private string BuildBackupPathWithFilename(string databaseName)
          {
              string filename = string.Format("{0}-{1}.bak", databaseName, DateTime.Now.ToString("yyyy-MM-dd"));
      
              return Path.Combine(_backupFolderFullPath, filename);
          }
      }
      

      【讨论】:

      • 三年过去了,但它仍然非常完美。非常感谢。
      • 嗨,朋友,如果我只想备份一个表,它可以工作吗?
      【解决方案4】:

      下面Link已经详细解释了如何使用c#备份sql server 2008数据库

      Sql 数据库备份可以通过多种方式完成。您可以像其他答案一样使用 Sql 命令,也可以创建自己的类来备份数据。

      但这些是不同的备份模式。

      1. 完整的数据库备份
      2. 差异数据库备份
      3. 事务日志备份
      4. 压缩备份

      但是这种方法的缺点是需要在你的客户端系统上安装你的sql management studio。

      【讨论】:

      • SMO 表示 SQL 管理对象安装在本地执行 .NET 备份程序的机器上,纯 SQL 解决方案没有。
      • 在某些时候,我需要使用 SMO,我只是放弃了,所有 sql 文件夹中的 DLL 文件都没有(您可能会在不同的文件夹中找到相同 DLL 的不同版本)可以匹配,即使是 NuGet 版本也不提供匹配版本的 DLL 文件
      【解决方案5】:
                  SqlConnection con = new SqlConnection();
                  SqlCommand sqlcmd = new SqlCommand();
                  SqlDataAdapter da = new SqlDataAdapter();
                  DataTable dt = new DataTable();
      
                  con.ConnectionString = ConfigurationManager.ConnectionStrings["MyConString"].ConnectionString;
                  string backupDIR = "~/BackupDB";
                  string path = Server.MapPath(backupDIR);
      
                  try
                  {
                      var databaseName = "MyFirstDatabase";
                      con.Open();
                      string saveFileName = "HiteshBackup";
                      sqlcmd = new SqlCommand("backup database" +databaseName.BKSDatabaseName + "to disk='" + path + "\\" + saveFileName + ".Bak'", con);
                      sqlcmd.ExecuteNonQuery();
                      con.Close();                 
      
      
                      ViewBag.Success = "Backup database successfully";
                      return View("Create");
                  }
                  catch (Exception ex)
                  {
                      ViewBag.Error = "Error Occured During DB backup process !<br>" + ex.ToString();
                      return View("Create");
                  }
      

      【讨论】:

        【解决方案6】:

        我有没有 SMO 问题的新方法

        1.使用备份 sqlcmd 命令创建 .bat 文件

        用于备份

        SqlCmd -E -S Server_Name –Q “BACKUP DATABASE [Name_of_Database] TO DISK=’X:PathToBackupLocation[Name_of_Database].bak'”
        

        恢复

        SqlCmd -E -S Server_Name –Q “RESTORE DATABASE [Name_of_Database] FROM DISK=’X:PathToBackupFile[File_Name].bak'”
        

        2。使用 WPF/C# 代码运行 bat 文件

                FileInfo file = new FileInfo("DB\\batfile.bat");
                Process process = new Process();
                process.StartInfo.FileName = file.FullName;
                process.StartInfo.Arguments = @"-X";
                process.StartInfo.WindowStyle = ProcessWindowStyle.Normal;
                process.StartInfo.UseShellExecute = false; //Changed Line
                process.StartInfo.RedirectStandardOutput = true;  //Changed Line
                process.Start();
                string output = process.StandardOutput.ReadToEnd(); //Changed Line
                process.WaitForExit(); //Moved Line
        

        【讨论】:

        • 谢谢...但是如果服务器包含用户名和密码怎么办?
        • 我也在搜索那个答案
        【解决方案7】:

        这对我有用...

        private void BackupButtonClick(object sender, RoutedEventArgs e)
        {
            // FILE NAME WITH DATE DISTICNTION
            string fileName = string.Format("SchoolBackup_{0}.bak", DateTime.Now.ToString("yyyy_MM_dd_h_mm_tt"));
            try
            {
                // YOUR SEREVER OR MACHINE NAME
                Server dbServer = new Server (new ServerConnection("DESKTOP"));
                Microsoft.SqlServer.Management.Smo.Backup dbBackup = new Microsoft.SqlServer.Management.Smo.Backup()
                {
                    Action = BackupActionType.Database, 
                    Database = "School"
                };
        
                dbBackup.Devices.AddDevice(@backupDirectory() +"\\"+ fileName, DeviceType.File);
                dbBackup.Initialize = true;
                dbBackup.SqlBackupAsync(dbServer);
        
        
                MessageBox.Show("Backup", "Backup Completed!");
            }
            catch(Exception err)
            {
                System.Windows.MessageBox.Show(err.ToString());
            }
        }
        
        
        // THE DIRECTOTRY YOU WANT TO SAVE IN
        public string backupDirectory()
        {
            using (var dialog = new FolderBrowserDialog())
            {
                var result = dialog.ShowDialog();
                return dialog.SelectedPath;
            }
        }
        

        【讨论】:

          【解决方案8】:

          您可以使用以下查询来备份和还原,您必须更改备份路径

          数据库名称=[数据]

          备份:

          BACKUP DATABASE [data] TO  DISK = N'C:\Program Files\Microsoft SQL Server\MSSQL10_50.MSSQLSERVER\MSSQL\Backup\data.bak' WITH NOFORMAT, NOINIT,  NAME = N'data-Full Database Backup', SKIP, NOREWIND, NOUNLOAD,  STATS = 10
          GO
          

          恢复:

          RESTORE DATABASE [data] FROM  DISK = N'C:\Program Files\Microsoft SQL Server\MSSQL10_50.MSSQLSERVER\MSSQL\Backup\data.bak' WITH  FILE = 1,  NOUNLOAD,  REPLACE,  STATS = 10
          GO
          

          【讨论】:

          • 这个答案和火了四年的this answer有什么不同?
          【解决方案9】:
           private void BackupManager_Load(object sender, EventArgs e)
                  {
                      txtFileName.Text = "DB_Backup_" + DateTime.Now.ToString("dd-MMM-yy");
                  }
          
                  private void btnDBBackup_Click(object sender, EventArgs e)
                  {
                      if (!string.IsNullOrEmpty(txtFileName.Text.Trim()))
                      {
                          BackUp();
                      }
                      else
                      {
                          MessageBox.Show("Please Enter Backup File Name", "", MessageBoxButtons.OK, MessageBoxIcon.Information);
                          txtFileName.Focus();
                          return;
                      }
                  }
          
                  private void BackUp()
                  {
                      try
                      {
          
                          progressBar1.Value = 0;
          
                          for (progressBar1.Value = 0; progressBar1.Value < 100; progressBar1.Value++)
                          {
          
                          }
          
                          pl.DbName = "Inventry";
                          pl.Path = @"D:/" + txtFileName.Text.Trim() + ".bak";
          
                          for (progressBar1.Value = 100; progressBar1.Value < 200; progressBar1.Value++)
                          {
          
                          }
          
                          bl.DbBackUp(pl);
                          for (progressBar1.Value = 200; progressBar1.Value < 300; progressBar1.Value++)
                          {
          
                          }
          
                          for (progressBar1.Value = 300; progressBar1.Value < 400; progressBar1.Value++)
                          {
          
                          }
          
                          for (progressBar1.Value = 400; progressBar1.Value < progressBar1.Maximum; progressBar1.Value++)
                          {
          
                          }
                          if (progressBar1.Value == progressBar1.Maximum)
                          {
                              MessageBox.Show("Backup Saved Successfully...!!!", "", MessageBoxButtons.OK, MessageBoxIcon.Information);
                          }
                          else
                          {
                              MessageBox.Show("Action Failed, Please try again later", "", MessageBoxButtons.OK, MessageBoxIcon.Error);
                          }
                      }
          
                      catch (Exception ex)
                      {
                          MessageBox.Show("Action Failed, Please try again later", "", MessageBoxButtons.OK, MessageBoxIcon.Error);
                      }
                      finally
                      {
                          progressBar1.Value = 0;
                      }
                  }
          

          【讨论】:

            【解决方案10】:

            您可以使用 C# 对 SQL Server 实例进行数据库备份,如下所示

            第 1 步:安装 Nuget 包“Install-Package Microsoft.SqlServer.SqlManagementObjects

            第 2 步:使用以下 C# 命令使用自定义功能进行备份

            public void BackupDatabase(string databaseName, string userName, string password, string serverName, string destinationPath)
            
             {  
            //Define a Backup object variable.
            Backup sqlBackup = new Backup();
            //Specify the type of backup, the description, the name, and the database to be backed up.
            sqlBackup.Action = BackupActionType.Database;
            
            sqlBackup.BackupSetDescription = "BackUp of:" + databaseName + "on" + DateTime.Now.ToShortDateString();
            
            sqlBackup.BackupSetName = "FullBackUp";
            
            sqlBackup.Database = databaseName;
            //Declare a BackupDeviceItem
            BackupDeviceItem deviceItem = new BackupDeviceItem(destinationPath + "FullBackUp.bak", DeviceType.File);
            
            //Define Server connection
            ServerConnection connection = new ServerConnection(serverName, userName, password); //To Avoid TimeOut Exception
            Server sqlServer = new Server(connection);
            sqlServer.ConnectionContext.StatementTimeout = 60 * 60;
            Database db = sqlServer.Databases[databaseName];
            (Reference Database As microsoft.sqlserver.management.smo.database, not as System.entity.database)
            
            sqlBackup.Initialize = true;
            
            sqlBackup.Checksum = true;
            
            sqlBackup.ContinueAfterError = true;
            //Add the device to the Backup object.
            sqlBackup.Devices.Add(deviceItem);
            
            //Set the Incremental property to False to specify that this is a full database backup. 
            sqlBackup.Incremental = false;
            sqlBackup.ExpirationDate = DateTime.Now.AddDays(3);
            
            //Specify that the log must be truncated after the backup is complete.        
            sqlBackup.LogTruncation = BackupTruncateLogType.Truncate;
            sqlBackup.FormatMedia = false;
            
            //Run SqlBackup to perform the full database backup on the instance of SQL Server. 
            sqlBackup.SqlBackup(sqlServer);
            
            //Remove the backup device from the Backup object.           
             sqlBackup.Devices.Remove(deviceItem);
            
            }
            

            添加引用

            Microsoft.SqlServer.ConnectionInfo
            Microsoft.SqlServer.Management.Sdk.Sfc
            Microsoft.SqlServer.Smo
            Microsoft.SqlServer.SmoExtended
            Microsoft.SqlServer.SqlEnum
            

            就是这样,大功告成,它将在指定位置备份指定数据库并传递给函数。

            来源:Various ways to back up SQL server database

            注意:用户必须有适当的权限才能将备份数据写入指定的磁盘位置。

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 2021-08-11
              • 2011-04-26
              • 1970-01-01
              • 2012-06-28
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2011-05-26
              相关资源
              最近更新 更多