简体   繁体   English

使用C#将SQL Server 2008数据库备份到sql文件(如.sql)

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

How to take Backup SQL Server 2008 database to a sql file(like .sql) using c# 如何使用C#将Backup SQL Server 2008数据库带到sql文件(如.sql)

I am creating a program that uses a simple database with only a few tables. 我正在创建一个仅使用几个表的简单数据库的程序。 I need to do a backup and restore of the database to and from a SQLfile like a .SQL. 我需要在SQL文件(如.SQL)之间进行数据库的备份和还原。 How can i do it.. 我该怎么做..

Thank You 谢谢

You can take the database backup using SQL Server backup wizard or using SQL Server BackUp Database statement 您可以使用SQL Server备份向导或使用SQL Server BackUp Database语句进行数据库备份

SQL Server Management Objects (SMO) is a collection of objects that are designed for programming all aspects of managing Microsoft SQL Server. SQL Server管理对象(SMO)是对象的集合,这些对象旨在用于对管理Microsoft SQL Server的所有方面进行编程。

For taking the database backup using C#, you have to add the following references in your application- 为了使用C#进行数据库备份,您必须在应用程序中添加以下引用-

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

In your .CS file you will have to use the following namespaces- 在您的.CS文件中,您将必须使用以下命名空间-

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

After using above namespaces, write the following code to take the database backup- 使用上述名称空间后,编写以下代码以备份数据库-

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

Use SQL Server's Generate Scripts commend 使用SQL Server的“生成脚本”推荐

right click on the database; 右键单击数据库; Tasks -> Generate Scripts 任务->生成脚本

  1. select your tables, click Next 选择表,单击下一步
  2. click the Advanced button 点击高级按钮
  3. find Types of data to script - choose Schema and Data. 找到要编写脚本的数据类型-选择“架构和数据”。
  4. you can then choose to save to file, or put in new query window. 然后,您可以选择保存到文件或放入新的查询窗口。
  5. results in CREATE and INSERT statements for all table data selected in bullet 2. 对项目符号2中选择的所有表数据生成CREATE和INSERT语句。

看到这张图片

try this 尝试这个

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

i was wasting my 2 days on this hope its helpfull for u 我在这个希望上浪费了我的两天时间,这对你有帮助

and important thing don't forgot to add reference 重要的事情不要忘记添加参考

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