NetCore에서 SQLServer 데이터베이스를 Sql 스크립트로 백업

설명하다:

최근에 데이터베이스를 Sql 스크립트로 백업하는 프로젝트를 작성해 달라는 요청을 받았는데 SQL ServerMy Sql 이라고 해도 되지만 인터넷 검색을 많이 해보니 다 방법을 가르쳐 주신다. 작동하려면 SSMS매우 고통 스럽습니다!

해결책:

다양한 검색 자료와 몇몇 형제들의 도움을 통해 해결책을 찾았습니다.

Microsoft.SqlServer.Management.SmoMicrosoft.SqlServer.Management.Sdk.Sfc,  를 통해 Microsoft.SqlServer.Management.Common해결하지만 안타깝게도 이 방법은 적용 가능할 수 있으며 .Net FrameworkMicrosoft는 로 캡슐화된 클래스 라이브러리 모음을 제공했습니다 Microsoft.SqlServer.Scripts.하지만 저는 Net5프로젝트입니다!

그러나 마침내 그것을 발견했습니다. Microsoft는 다른 패키지를 패키징했습니다 ... emm 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