c# 使用数据库中的数据生成 INSERT 脚本

问题描述 投票:0回答:3

我尝试生成一个包含 INSERT 脚本表单中的数据的脚本, 我尝试使用参考(见下文)来做到这一点

using Microsoft.SqlServer.Management.Smo;

使用此代码草案

Server serv = new Server(db);
Database simba = serv.Databases[dbname];
string script = "";

ScriptingOptions so = new ScriptingOptions()
{
    ScriptData = true,
    ScriptSchema = false,
    ScriptDrops = false
};

foreach (Table tb in simba.Tables)
{
    if (tables.Contains(tb.Name))
    {
        var sc = tb.Script(so);
        foreach (var s in sc)
            script += s;

    }
    using (StreamWriter writer = new StreamWriter(file))
    {
        foreach (string tab in tables)
        writer.WriteLine(script);
    }
}

但是这段代码出现错误

var sc = tb.Script(so);

这是

Microsoft.SqlServer.Management.Smo.FailedOperationException

谢谢大家的回复

c# sql-server smo
3个回答
4
投票

我有这个代码,它工作正常尝试使用它

var report   = string.Empty;
var fileName = Server.MapPath(Constants.BACKUP_FILE_NAME);

var server      = new Server(new ServerConnection(new SqlConnection(Constants.BACKUP_CONNECTION_STRING)));
var options     = new ScriptingOptions();
var databases   = server.Databases[Constants.BACKUP_DATABASE_NAME];                    

options.FileName                = fileName;
options.EnforceScriptingOptions = true;
options.WithDependencies        = true;
options.IncludeHeaders          = true;
options.ScriptDrops             = false;
options.AppendToFile            = true;
options.ScriptSchema            = true;
options.ScriptData              = true;
options.Indexes                 = true;

report = "<h4>Table Scripts</h4>";
foreach (var table in Constants.BACKUP_TABLES)
{
    databases.Tables[table, Constants.BACKUP_SCHEMA_NAME].EnumScript(options);                        
    report += "Script Generated: " + table + "<br>";
}

“常量”是我的类,用于保存文件名、数据库等常量值,我正在为有限的表生成脚本,因此,不要像在代码中那样执行“simba.Tables”;如果您希望生成每个表脚本,您当然可以这样做。所以这段代码生成脚本并将其存储到指定的文件中。

希望有帮助


3
投票

谢谢@Zaki Mohammed,

你的代码对我帮助很大,

我只是根据我的情况做了一些修改,它就完美地工作了,

            Server serv = new Server(db);
            Database simba = serv.Databases[dbname];
            Scripter scripter = new Scripter(serv);
            scripter.Options.FileName = "InsertIntoScript.sql";
            scripter.Options.EnforceScriptingOptions = true;
            scripter.Options.WithDependencies = false;
            scripter.Options.IncludeHeaders = true;
            scripter.Options.ScriptDrops = false;
            scripter.Options.AppendToFile = true;
            scripter.Options.ScriptSchema = false;
            scripter.Options.ScriptData = true;
            scripter.Options.Indexes = false;

            string script = "";
            foreach (Table tb in simba.Tables)
            {
                if (tables.Contains(tb.Name))
                {
                    IEnumerable<string> sc = scripter.EnumScript(new Urn[] { tb.Urn });
                    foreach (var s in sc)
                        script += s;
                }
            }

0
投票
    static void Main(string[] args)
    {
        string serverName = @"xxxxx\SQLEXPRESS";
        string databaseName = "databaseName";
        string outputPath = "C:\\ScriptFile1.sql";
        string connectionString = $"Server={serverName};Database={databaseName};Integrated Security=true;";

        try
        {
            GenerateInsertScript(connectionString, outputPath);
            Console.WriteLine($"Insert script generated successfully: {outputPath}");
            Console.ReadKey();
        }
        catch (Exception ex)
        {
            Console.WriteLine($"Error: {ex.Message}");
        }
    }
    static void GenerateInsertScript(string connectionString, string outputPath)
    {
        SqlConnection connection = new SqlConnection(connectionString + ";MultipleActiveResultSets=True");
        connection.Open();

        using (StreamWriter writer = new StreamWriter(outputPath))
        {
            SqlCommand command = new SqlCommand("SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE = 'BASE TABLE'", connection);
            SqlDataReader reader = command.ExecuteReader();

            while (reader.Read())
            {
                string tableName = reader.GetString(0);
                GenerateInsertStatements(connection, tableName, writer);
            }
        }
    }
    static void GenerateInsertStatements(SqlConnection connection, string tableName, StreamWriter writer)
    {
        SqlCommand selectCommand = new SqlCommand($"SELECT * FROM {tableName}", connection);
        SqlDataReader dataReader = selectCommand.ExecuteReader();



        if (dataReader.HasRows)
        {
            StringBuilder columns = new StringBuilder();
            StringBuilder values = new StringBuilder();
            for (int i = 0; i < dataReader.FieldCount; i++)
            {
                columns.Append($"{dataReader.GetName(i)}, ");
                values.Append($"@{dataReader.GetName(i)}, ");
            }

            columns.Length -= 2; // Remove the trailing comma and space
            values.Length -= 2; // Remove the trailing comma and space


            writer.WriteLine($"-- Insert statements for {tableName}");
            writer.WriteLine($"INSERT INTO {tableName} ({columns.ToString()}) VALUES");

            while (dataReader.Read())
            {
                writer.Write("(");
                for (int i = 0; i < dataReader.FieldCount; i++)
                {
                    if (dataReader.FieldCount - 1 == i)
                    {
                        writer.Write($"'{EscapeSqlString(dataReader[i].ToString())}' ");
                    }
                    else
                    {
                        writer.Write($"'{EscapeSqlString(dataReader[i].ToString())}', ");
                    }
                }

                writer.WriteLine("),");
            }

        }
        writer.WriteLine();

    }
    static string EscapeSqlString(string input)
    {
        // Implement any necessary SQL string escaping logic here
        return input.Replace("'", "''");
    }
© www.soinside.com 2019 - 2024. All rights reserved.