Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/sql-server-2008/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 在C中通过SMO(SQL Server管理对象)进行数据库备份#_C#_Sql Server 2008_Smo - Fatal编程技术网

C# 在C中通过SMO(SQL Server管理对象)进行数据库备份#

C# 在C中通过SMO(SQL Server管理对象)进行数据库备份#,c#,sql-server-2008,smo,C#,Sql Server 2008,Smo,我需要备份数据库(使用SQL Server 2008 R2)。数据库的大小大约为100GB,所以我只需要备份重要表(包含设置)的内容,当然还有所有表、视图、触发器等的对象 例如: db:产品 表格:食物、衣服、汽车 cars中的车太多了,所以我只备份表定义(CREATE table…)并完成Food和cloth(包括其内容) 请告诉我最好的解决办法。我可能会使用SMO(如果没有更好的解决方案)。我应该使用备份类吗?还是Scripterclass?或者其他(如果有)?哪一类可以满足我的要求 我

我需要备份数据库(使用SQL Server 2008 R2)。数据库的大小大约为100GB,所以我只需要备份重要表(包含设置)的内容,当然还有所有表、视图、触发器等的对象

例如:

  • db:
    产品
  • 表格:
    食物、衣服、汽车
cars
中的车太多了,所以我只备份表定义(
CREATE table…
)并完成
Food
cloth
(包括其内容)

请告诉我最好的解决办法。我可能会使用SMO(如果没有更好的解决方案)。我应该使用
备份
类吗?还是
Scripter
class?或者其他(如果有)?哪一类可以满足我的要求

我希望将这些文件备份到
*.sql
文件,如果可能,每个表一个

我将感谢代码示例。写在回答或某处(张贴url),但要确保外部文章有解决这类问题的确切方法

您可以使用这部分代码

ServerConnection connection = new ServerConnection("SERVER,1234", "User", "User1234");
Server server = new Server(connection);
Database database = server.Databases["DbToBackup"];

您所描述的并不是真正的备份,但我理解您的目标:


对于数据的“备份”,您可以通过
读取器
将表内容加载到
数据表
中,并使用SMO将结果存储为XML…

。你将不得不使用你需要的选项

StringBuilder sb = new StringBuilder();
using (SqlConnection connection = new SqlConnection("connectionString")) {
    ServerConnection serverConnection = new ServerConnection(connection);
    Server server = new Server(serverConnection);
    Database database = server.Databases["databaseName"];
    Scripter scripter = new Scripter(server);
    scripter.Options.ScriptDrops = false;
    scripter.Options.WithDependencies = true;
    scripter.Options.ScriptData = true;
    Urn[] smoObjects = new Urn[1];
    foreach (Table table in database.Tables) {
        smoObjects[0] = table.Urn;
        if (!table.IsSystemObject) {
            foreach (string s in scripter.EnumScript(smoObjects)) {
                System.Diagnostics.Debug.WriteLine(s);
                sb.AppendLine(s);
            }
        }
    }
}
// Write to *.sql file on disk
File.WriteAllText(@".\backup.sql");
另一种简单的方法是将数据库备份到xml文件。为此,请使用DataTable并调用WriteXml和WriteXmlSchema。(稍后需要该架构,以便可以使用相同的方法导入/还原它)。此方法意味着您要备份每个表

private bool BackupTable(string connectionString, string tableName, string directory) {
    using (SqlConnection connection = new SqlConnection(connectionString)) {
        try {
            connection.Open();
        }
        catch (System.Data.SqlClient.SqlException ex) {
            // Handle
            return false;
        }
        using (SqlDataAdapter adapter = new SqlDataAdapter(string.Format("SELECT * FROM {0}", tableName), connection)) {
            using (DataTable table = new DataTable(tableName)) {
                adapter.Fill(table);
                try {
                    table.WriteXml(Path.Combine(directory, string.Format("{0}.xml", tableName)));
                    table.WriteXmlSchema(Path.Combine(directory, string.Format("{0}.xsd", tableName)));
                }
                catch (System.UnauthorizedAccessException ex) {
                    // Handle
                    return false;
                }
            }
        }
    }
    return true;
}
稍后,您可以使用ReadXmlSchema和ReadXml,使用适配器将表填充并更新到数据库中,从而将这些内容推回到数据库us中。我想你对基本积垢很在行,所以我不需要讨论这一部分

如果您想使用SMO,这里有一篇Msdn文章,介绍如何使用备份和还原类来备份和还原数据库。代码示例我们未格式化,在VB.NET中,但易于翻译

最后,这可能更容易,与IT人员交谈,看看他们是否会让您远程进入,或者让您自己进行备份。如果您正在编写软件,而这是一个关键步骤,请大声说出来,让他们知道这样做对您来说有多重要,因为这将降低您在已有优秀工具的情况下编写自定义工具的成本。特别是由于数据库是100GB,您可以使用您知道已经可以使用的工具

arcitle提供了足够的信息来解决我的问题。这是我的工作方案。 我决定将所有对象脚本化为一个文件,我认为这是更好的解决方案,因为依赖性。如果每个文件上都有一个表,并且还有一些依赖项(例如外键),那么它将编写比所有内容都在一个文件中更多的代码

在这个示例中,我省略了一些代码,比如备份文件以防错误的数据库备份。如果没有这样一个系统,所有备份都将脚本化到一个文件中,并且会变得一团糟

public class DatabaseBackup
{
    private ServerConnection Connection;
    private Server Server;
    private Database Database;
    private ScriptingOptions Options;
    private string FileName;
    private const string NoDataScript = "Cars";

    public DatabaseBackup(string server, string login, string password, string database)
    {
        Connection = new ServerConnection(server, login, password);
        Server = new Server(Connection);
        Database = Server.Databases[database];
    }

    public void Backup(string fileName)
    {
        FileName = fileName;
        SetupOptions();

        foreach (Table table in Database.Tables)
        {
             if (!table.IsSystemObject)
             {
                  if (NoDataScript.Contains(table.Name))
                  {
                       Options.ScriptData = false;
                       table.EnumScript(Options);
                       Options.ScriptData = true;
                  }
                  else
                       table.EnumScript(Options);
              }
         }
    }

    private void SetupOptions()
    {
         Options = new ScriptingOptions();
         Options.ScriptSchema = true;
         Options.ScriptData = true;
         Options.ScriptDrops = false;
         Options.WithDependencies = true;
         Options.Indexes = true;
         Options.FileName = FileName;
         Options.EnforceScriptingOptions = true;
         Options.IncludeHeaders = true;
         Options.AppendToFile = true;
    }
}
Server-databaseServer=default(服务器)//数据库服务器名称
databaseServer=新服务器(“ecrisqlstddev”);
字符串strFileName=@“C:\Images\UltimateSurveyMod_u3;”+DateTime.Today.ToString(“yyyyMMdd”)+“.sql”//20120720
if(System.IO.File.Exists(strFileName))
System.IO.File.Delete(strFileName);
列表=新列表();
Scripter Scripter=新的脚本编写器(数据库服务器);
Database dbUltimateSurvey=databaseServer.Databases[“UltimateSurvey”]//数据库名称
//表脚本编写
DataTable dataTable1=dbUltimateSurvey.EnumObjects(DatabaseObjectTypes.Table);
foreach(dataTable1.Rows中的DataRow drTable)
{
//字符串strTableSchema=(字符串)drTable[“Schema”];
//if(strTableSchema==“dbo”)
//继续;
Table dbTable=(Table)databaseServer.GetSmoObject(新Urn((string)drTable[“Urn”]);
如果(!dbTable.IsSystemObject)
if(dbTable.Name.Contains(“SASTool”))
list.Add(dbTable);
}
scripter.Server=数据库服务器;
scripter.Options.IncludeHeaders=true;
scripter.Options.SchemaQualify=true;
scripter.Options.ToFileOnly=true;
scripter.Options.FileName=strFileName;
scripter.Options.DriAll=true;
scripter.Options.AppendToFile=true;
scripter.Script(list.ToArray());//表脚本已完成
//存储过程脚本编写
列表=新列表();
DataTable DataTable=dbUltimateSurvey.EnumObjects(DatabaseObjectTypes.StoredProcess);
foreach(dataTable.Rows中的DataRow行)
{
字符串sSchema=(字符串)行[“架构”];
如果(sSchema==“系统”| | sSchema==“信息模式”)
继续;
StoredProcedure sp=(StoredProcedure)databaseServer.GetsObject(
新Urn((字符串)行[“Urn”]);
如果(!sp.IsSystemObject)
if(sp.Name.Contains(“自定义”)
列表。添加(sp);
}
scripter.Server=数据库服务器;
scripter.Options.IncludeHeaders=true;
scripter.Options.SchemaQualify=true;
scripter.Options.ToFileOnly=true;
scripter.Options.FileName=strFileName;
scripter.Options.DriAll=true;
scripter.Options.AppendToFile=true;
scripter.Script(list.ToArray());//存储过程脚本已完成

为什么不能通过SQL Management Studio进行备份?因为它不是我的服务器。我只为客户端编写应用程序代码。他是个新手,他不能自己做。常规SQL Server备份只能在数据库或文件组级别工作-您不能有选择地备份某些表而忽略其他表。如果要将脚本输出到SQL,则需要使用SMO和
Scripter
类-不确定该类是否也支持将表的内容脚本输出-您必须尝试。True,但您可以有选择地将数据输出为可重用的格式“备份”是上下文相关的。Thx发送到marc_s以编辑我的文章。这个看起来像b
Server databaseServer = default(Server);//DataBase Server Name
databaseServer = new Server("ecrisqlstddev");

string strFileName = @"C:\Images\UltimateSurveyMod_" + DateTime.Today.ToString("yyyyMMdd") + ".sql"; //20120720

if (System.IO.File.Exists(strFileName))
    System.IO.File.Delete(strFileName);

List<SqlSmoObject> list = new List<SqlSmoObject>();
Scripter scripter = new Scripter(databaseServer);

Database dbUltimateSurvey = databaseServer.Databases["UltimateSurvey"];//DataBase Name

// Table scripting Writing
DataTable dataTable1 = dbUltimateSurvey.EnumObjects(DatabaseObjectTypes.Table);

foreach (DataRow drTable in dataTable1.Rows)
{
    // string strTableSchema = (string)drTable["Schema"];
    // if (strTableSchema == "dbo")
    //    continue;
    Table dbTable = (Table)databaseServer.GetSmoObject(new Urn((string)drTable["Urn"]));

    if (!dbTable.IsSystemObject)
        if (dbTable.Name.Contains("SASTool_"))
            list.Add(dbTable);
}

scripter.Server = databaseServer;

scripter.Options.IncludeHeaders = true;
scripter.Options.SchemaQualify = true;
scripter.Options.ToFileOnly = true;
scripter.Options.FileName = strFileName;
scripter.Options.DriAll = true;
scripter.Options.AppendToFile = true;

scripter.Script(list.ToArray());     // Table Script completed

// Stored procedures scripting writing
list = new List<SqlSmoObject>();

DataTable dataTable = dbUltimateSurvey.EnumObjects(DatabaseObjectTypes.StoredProcedure);

foreach (DataRow row in dataTable.Rows)
{
    string sSchema = (string)row["Schema"];

    if (sSchema == "sys" || sSchema == "INFORMATION_SCHEMA")
        continue;

    StoredProcedure sp = (StoredProcedure)databaseServer.GetSmoObject(
               new Urn((string)row["Urn"]));

    if (!sp.IsSystemObject)
        if (sp.Name.Contains("custom_"))
            list.Add(sp);
}

scripter.Server = databaseServer;

scripter.Options.IncludeHeaders = true;
scripter.Options.SchemaQualify = true;
scripter.Options.ToFileOnly = true;
scripter.Options.FileName = strFileName;
scripter.Options.DriAll = true;
scripter.Options.AppendToFile = true;

scripter.Script(list.ToArray());    // Stored procedures script completed