NetCore で SQLServer データベースを SQL スクリプトとしてバックアップする

説明:

最近、データベースを SQL スクリプトとしてバックアップするというプロジェクトの作成の依頼を受けました。My SQL ServerSQL であれば大丈夫ですが、インターネットでたくさん検索しました。そのすべてが方法を教えてくれます。操作するのはSSMS、とても痛いです!

解決:

さまざまな検索資料と何人かの兄弟たちの助けを通じて、私は解決策を見つけました。

Microsoft.SqlServer.Management.Smoを 介して解決しますMicrosoft.SqlServer.Management.Sdk.Sfcが、 Microsoft.SqlServer.Management.Common残念ながら、この方法は にのみ適用できる可能性があり.Net Framework、Microsoft は としてカプセル化されたクラス ライブラリのコレクションを提供していますMicrosoft.SqlServer.Scripts。しかし、私はNet5プロジェクトです。

しかし、最終的には、Microsoft が別のパッケージをパッケージ化したことがわかりました...えっとMicrosoft.SqlServer.SqlManagementObjects、この種のライブラリは に適用できますNet Core

基本的な使い方

Server server = new Server(
    new ServerConnection(
        // 服务器IP
        _dbBackupOptions.ServerInstance,
        // 登录名
        _dbBackupOptions.Username,
        // 密码
        _dbBackupOptions.Password
        )
);
// 获取数据库
Database templateDb = server.Databases[_dbBackupOptions.DatabaseName];
// 脚本导出路径
string sqlFilePath = string.Format("{0}.sql", $"{dbBackupPath}/{name}");
// 自定义规则
var startWith = _dbBackupOptions.FormatTables.Where(x => x.EndsWith("*")).Select(x => x.TrimEnd('*'));
var endWith = _dbBackupOptions.FormatTables.Where(x => x.StartsWith("*")).Select(x => x.TrimStart('*'));

if (_dbBackupOptions.FormatTables is not null && _dbBackupOptions.FormatTables.Any())
{
    foreach (Table tb in templateDb.Tables)
    {
        if (_dbBackupOptions.FormatTables.Contains(tb.Name) ||
            startWith.Where(x => tb.Name.StartsWith(x)).Any() ||
            endWith.Where(x => tb.Name.EndsWith(x)).Any())
        {
            // 按表获取Sql
            IEnumerable<string> sqlStrs = tb.EnumScript(_dbBackupOptions.ScriptingOptions);
            // 将Sql向文件中追加
            using (StreamWriter sw = new StreamWriter(sqlFilePath, true, Encoding.UTF8))
            {
                foreach (var sql in sqlStrs)
                {
                    sw.WriteLine(sql);
                    sw.WriteLine("GO");
                }
            }
        }
    }
}
else
{
    foreach (Table tb in templateDb.Tables)
    {
        IEnumerable<string> sqlStrs = tb.EnumScript(_dbBackupOptions.ScriptingOptions);
        using (StreamWriter sw = new StreamWriter(sqlFilePath, true, Encoding.UTF8))
        {
            foreach (var sql in sqlStrs)
            {
                sw.WriteLine(sql);
                sw.WriteLine("GO");
            }
        }
    }
}

すぐに使える (パッケージ ライブラリ Powers.DbBackup)

Powers.DBackupこのために、便利で使いやすいクラス ライブラリをカプセル化しました 。

GitHub アドレス:  Powers.DbBackup

DbBackup の構成

1.  Startup.cs(Net5):

services.AddDbBackup();

appsettings.json:

"DbBackupOptions": {
    // remote server
    "ServerInstance": "192.168.31.36",
    // database username
    "Username": "sa",
    // password
    "Password": "sa123.",
    // ddatabase name
    "DatabaseName": "PumInfoShop",
    // output options
    "ScriptingOptions": {
      "DriAll": false,
      "ScriptSchema": true,
      "ScriptData": true,
      "ScriptDrops": false
    },
    // match rules
    /**
     * Include 3 rules:
     * 1. Full name: UserTable
     * 2. Start with: Sys*
     * 3. End with: *Table
     */
    "FormatTables": []
  }

また

services.AddDbBackup(opts =>
{
    opts.ServerInstance = "127.0.0.1";
    opts.Username = "sa";
    opts.Password = "123456";
    opts.DatabaseName = "TestDb";
    opts.ScriptingOptions = new ScriptingOptions
    {
        DriAll = true,
        ScriptSchema = true,
        ScriptData = true,
        ScriptDrops = false
    };
    /**
     * Include 3 rules:
     * 1. Full name: UserTable
     * 2. Start with: Sys*
     * 3. End with: *Table
     */
    opts.FormatTables = new string[] { "Sys*", "Log*", "UserTable", "*Table" };
});
// Or this way
//services.AddDbBackup(opts => new DbBackupOptions
//{
//    ServerInstance = "127.0.0.1",
//    Username = "sa",
//    // .....
//});

2.  Program.cs(Net6):

builder.Services.AddDbBackup();

appsettings.json:

"DbBackupOptions": {
    "ServerInstance": "192.168.31.36",
    "Username": "sa",
    "Password": "sa123.",
    "DatabaseName": "PumInfoShop",
    "ScriptingOptions": {
      "DriAll": false,
      "ScriptSchema": true,
      "ScriptData": true,
      "ScriptDrops": false
    },
    "FormatTables": []
  }

また

builder.Services.AddDbBackup(opts =>
{
    opts.ServerInstance = "127.0.0.1";
    opts.Username = "sa";
    opts.Password = "123456";
    opts.DatabaseName = "TestDb";
    opts.ScriptingOptions = new ScriptingOptions
    {
        DriAll = true,
        ScriptSchema = true,
        ScriptData = true,
        ScriptDrops = false
    };
    /**
     * Include 3 rules:
     * 1. Full name: UserTable
     * 2. Start with: Sys*
     * 3. End with: *Table
     */
    opts.FormatTables = new string[] { "Sys*", "Log*", "UserTable", "*Table" };
});

// Or this way
//builder.Services.AddDbBackup(opts => new DbBackupOptions
//{
//    ServerInstance = "127.0.0.1",
//    Username = "sa",
//    // .....
//});

手順

[HttpGet]
public async Task<ActionResult> StartDbBackup()
{
    var rootPath = "D:/";
    var fileName = DateTime.Now.ToString("yyyyMMddhhmmss"); // No ".sql" suffix is required.
    var (path, size) = await DbBackupExtensions.StartBackupAsync(rootPath, fileName);// path is full path

    return Ok(new
    {
        Path = path,
        Size = size
    });
}

[HttpGet]
public async Task<ActionResult> DeleteDbBackup(string filePath)
{
    var (res, msg) = await DbBackupExtensions.DeleteBackup(filePath);

    if (res)
    {
        return Ok(msg);
    }
    else
    {
        return NotFound(msg);
    }
}

おすすめ

転載: blog.csdn.net/Z__7Gk/article/details/131853282