簡體   English   中英

使用C#將SQL Server 2008數據庫備份到sql文件(如.sql)

[英]Backup SQL Server 2008 database to a sql file(like .sql) using c#

如何使用C#將Backup SQL Server 2008數據庫帶到sql文件(如.sql)

我正在創建一個僅使用幾個表的簡單數據庫的程序。 我需要在SQL文件(如.SQL)之間進行數據庫的備份和還原。 我該怎么做..

謝謝

您可以使用SQL Server備份向導或使用SQL Server BackUp Database語句進行數據庫備份

SQL Server管理對象(SMO)是對象的集合,這些對象旨在用於對管理Microsoft SQL Server的所有方面進行編程。

為了使用C#進行數據庫備份,您必須在應用程序中添加以下引用-

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

在您的.CS文件中,您將必須使用以下命名空間-

using Microsoft.SqlServer.Management.Smo;
using Microsoft.SqlServer.Management.Common;

使用上述名稱空間后,編寫以下代碼以備份數據庫-

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];

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

使用SQL Server的“生成腳本”推薦

右鍵單擊數據庫; 任務->生成腳本

  1. 選擇表,單擊下一步
  2. 點擊高級按鈕
  3. 找到要編寫腳本的數據類型-選擇“架構和數據”。
  4. 然后,您可以選擇保存到文件或放入新的查詢窗口。
  5. 對項目符號2中選擇的所有表數據生成CREATE和INSERT語句。

看到這張圖片

嘗試這個

 try
                {
                StringBuilder resultScript = new StringBuilder(string.Empty);
                StringBuilder resultScript1 = new StringBuilder(string.Empty);
                var connStr = @"Data Source=.;Initial Catalog=MatrixEPOS;Integrated Security=True";
                var tables = new[] { "tblProductName", "tblProductSize", "tblProductType", "tblcheck", "tblcheckdetails", "tblSubProduct", "tblMeals", "tblMealDetails",
                "tblMealSizes","tblToppings","tblToppings1","tblToppingsSize","tblDressingSize"};
                ScriptingOptions scriptOptions = new ScriptingOptions();
                Server srv1 = new Server(".");
                Database db1 = srv1.Databases["MatrixEPOS"];
                StringBuilder sb = new StringBuilder();
                Urn[] ur;
                resultScript.AppendLine("Use MatrixEPOS");
                resultScript.AppendLine("GO");
                for(int i = 0; i < tables.Length; i++)
                    {

                    //  Table tbl = db1.Tables[tables[i]];
                    Scripter scr = new Scripter(srv1);

                    foreach(Table table in db1.Tables)
                        {
                        if(table.Name == tables[i].ToString())
                            {
                            // Only include lookup tables
                            if(table.ForeignKeys.Count == 0)
                                {
                                ScriptingOptions options = new ScriptingOptions();
                                options.DriAll = false;
                                options.ScriptSchema = false;
                                options.ScriptData = true;
                                scr.Options = options;

                                // Add script to file content 
                                foreach(string scriptLine in scr.EnumScript(new Urn[] { table.Urn }))
                                    {
                                    string line = scriptLine;
                                    line = line.Replace("SET ANSI_NULLS ON", string.Empty);
                                    line = line.Replace("SET QUOTED_IDENTIFIER ON", string.Empty);
                                    line = line.Replace("SET ANSI_NULLS OFF", string.Empty);
                                    line = line.Replace("SET QUOTED_IDENTIFIER OFF", string.Empty);
                                    resultScript.AppendLine(line.Trim());
                                    }
                                //resultScript1.AppendLine(table.Name);
                                //ur = table.Urn;
                                }
                            }
                        else { }
                        }
                    }
                string name12 = resultScript1 + ".sql";
                string fileName = string.Format("{0}.sql", "abc");
                File.WriteAllText(Path.Combine("G:\\", fileName), resultScript.ToString());
                }
            catch(Exception err)
                {
                Console.WriteLine(err.Message);
                }

我在這個希望上浪費了我的兩天時間,這對你有幫助

重要的事情不要忘記添加參考

using Microsoft.SqlServer.Management.Common;
using Microsoft.SqlServer.Management.Sdk.Sfc;
using Microsoft.SqlServer.Management.Smo;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM