Microsoft MVP성태의 닷넷 이야기
닷넷: 2207. C# - SQL Server DB를 bacpac으로 Export/Import [링크 복사], [링크+제목 복사],
조회: 2353
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일

C# - SQL Server DB를 bacpac으로 Export/Import

"Microsoft SSMS(SQL Server Management Studio)"의 기능 중에는 "Export Data-tier Application", "Import Data-tier Application" 메뉴를 이용해 DB를 bacpac 단일 파일로 export/import할 수 있습니다.

Data-tier applications (DAC)
; https://learn.microsoft.com/en-us/sql/relational-databases/data-tier-applications/data-tier-applications

Export to a BACPAC file - Azure SQL Database and Azure SQL Managed Instance
; https://learn.microsoft.com/en-us/azure/azure-sql/database/database-export

Azure 데이터베이스를 로컬 DB로 이전하는 방법
; https://www.sysnet.pe.kr/2/0/1667

재미있는 건, SSMS의 그런 기능들은 대부분 코드로도 가능하다는 점입니다. 실제로 bacpac 처리는 다음의 Q&A에도 그 방법이 나옵니다.

c# create a .bacpac file from ms sql database
; https://stackoverflow.com/questions/37705038/c-sharp-create-a-bacpac-file-from-ms-sql-database

즉, Microsoft.SqlServer.Dac.dll 어셈블리를 이용하면 되는데요, 비주얼 스튜디오를 설치한 경우 "C:\Program Files\Microsoft Visual Studio\2022\Enterprise\Common7\IDE\Extensions\Microsoft\SQLDB\DAC" 디렉터리에서 찾을 수 있습니다. 그런데 NuGet을 보면 동일한 이름의 패키지가 있는데,

// https://www.nuget.org/packages/Microsoft.SqlServer.Dac
Install-Package Microsoft.SqlServer.Dac

"Project website"의 링크가 단순히 learn 문서로 연결되는 것을 봤을 때 마이크로소프트의 공식 계정이 아니고 개인이 임의로 해당 DLL을 말아서 NuGet에 올린 것 같습니다.




bacpac 처리를 간단하게 ^^ 한번 만들어 볼까요?

우선 프로젝트 유형은 .NET Framework 유형으로 해야 합니다. (관련 DLL들이 아직은 .NET Core/5+용으로 빌드되지 않고 있습니다.)

그다음, Microsoft.SqlServer.Dac.dll과 함께 bacpac 처리에 필요한 DLL들은 (테스트로 알아낸 결과) 이렇게 필요합니다. (같은 디렉터리에 있습니다.)

  • Microsoft.Data.SqlClient.dll
  • Microsoft.Data.SqlClient.SNI.x64.dll
  • Microsoft.Data.Tools.Schema.Sql.dll
  • Microsoft.Data.Tools.Utilities.dll
  • Microsoft.Identity.Client.dll
  • Microsoft.SqlServer.Dac.dll
  • Microsoft.SqlServer.TransactSql.ScriptDom.dll
  • System.Memory.dll
  • System.Resources.Extensions.dll
  • System.Runtime.CompilerServices.Unsafe.dll

그중에 Microsoft.Data.SqlClient.SNI.x64.dll은 native 모듈이기 때문에 복사하는 식으로 배포하고, 다른 DLL들만 참조 추가를 하면 됩니다.

  <ItemGroup>
    <Content Include="..\lib\Microsoft.Data.SqlClient.SNI.x64.dll">
      <Link>Microsoft.Data.SqlClient.SNI.x64.dll</Link>
      <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
    </Content>
  </ItemGroup>

  <ItemGroup>
    <Reference Include="Microsoft.Data.SqlClient">
      <HintPath>..\lib\Microsoft.Data.SqlClient.dll</HintPath>
    </Reference>
    <Reference Include="Microsoft.Data.Tools.Schema.Sql">
      <HintPath>..\lib\Microsoft.Data.Tools.Schema.Sql.dll</HintPath>
    </Reference>
    <Reference Include="Microsoft.Data.Tools.Utilities">
      <HintPath>..\lib\Microsoft.Data.Tools.Utilities.dll</HintPath>
    </Reference>
    <Reference Include="Microsoft.Identity.Client">
      <HintPath>..\lib\Microsoft.Identity.Client.dll</HintPath>
    </Reference>
    <Reference Include="Microsoft.SqlServer.Dac">
      <HintPath>..\lib\Microsoft.SqlServer.Dac.dll</HintPath>
    </Reference>
    <Reference Include="Microsoft.SqlServer.TransactSql.ScriptDom">
      <HintPath>..\lib\Microsoft.SqlServer.TransactSql.ScriptDom.dll</HintPath>
    </Reference>
    <Reference Include="System.Memory, Version=4.0.1.2, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51, processorArchitecture=MSIL">
      <SpecificVersion>False</SpecificVersion>
      <HintPath>..\lib\System.Memory.dll</HintPath>
    </Reference>
    <Reference Include="System.Resources.Extensions">
      <HintPath>..\lib\System.Resources.Extensions.dll</HintPath>
    </Reference>
    <Reference Include="System.Runtime.CompilerServices.Unsafe, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
      <SpecificVersion>False</SpecificVersion>
      <HintPath>..\lib\System.Runtime.CompilerServices.Unsafe.dll</HintPath>
    </Reference>
  </ItemGroup>

자, 남은 것은 이제 코딩인데요, bacpack 파일로 export하는 것은 다음과 같이 할 수 있고,

using Microsoft.SqlServer.Dac;
using System;
using System.Data.SqlClient;
using System.IO;

namespace ConsoleApp1;

internal class Program
{
    static int Main(string[] args)
    {
        string infoFilePath = args[0];
        string downloadPath = args[1];

        SqlConnectionStringBuilder csb = new SqlConnectionStringBuilder();

        (string dataSource, string userId, string Password, string dbName) = LoadUserInfo(infoFilePath);

        string timePrefix = DateTime.Now.ToString("yyyy_MM_dd");
        string bacpacFilePath = Path.Combine(downloadPath, $"{dbName}_{timePrefix}.bacpac");

        csb.UserID = userId;
        csb.Password = Password;
        csb.DataSource = dataSource;
        csb.TrustServerCertificate = true;

        DacServices ds = new DacServices(csb.ConnectionString);
        ds.ExportBacpac(bacpacFilePath, dbName);

        Console.WriteLine(bacpacFilePath);

        return 0;
    }

    private static (string dataSource, string userId, string Password, string dbName) LoadUserInfo(string filePath)
    {
        string[] lines = File.ReadAllLines(filePath);
        return (lines[0], lines[1], lines[2], lines[3]);
    }
}

bacpac 파일을 다시 DB로 import하는 것은 다음과 같이 코딩할 수 있습니다.

using Microsoft.SqlServer.Dac;
using System;
using smo = Microsoft.SqlServer.Management.Smo;

namespace ConsoleApp3
{
    // Install-Package Microsoft.SqlServer.SqlManagementObjects 
    internal class Program
    {
        static int Main(string[] args)
        {
            string bacpacFilePath = args[0];
            string dbName = args[1];

            DropDatabaseIfExists(dbName);

            string connectionString = "TrustServerCertificate=true; Integrated Security=SSPI;Persist Security Info=False;Data Source=.";

            BacPackage bp = BacPackage.Load(bacpacFilePath);
            DacServices ds = new DacServices(connectionString);

            ds.ImportBacpac(bp, dbName);

            return 0;
        }

        private static void DropDatabaseIfExists(string dbName)
        {
            var server = new smo.Server(Environment.MachineName);
            smo.Database found = null;
            foreach (smo.Database db in server.Databases)
            {
                if (db.Name.Equals(dbName, StringComparison.InvariantCultureIgnoreCase))
                {
                    found = db;
                    break;
                }
            }

            if (found != null)
            {
                found.Drop();
            }
        }
    }
}




위의 코드를 이용하면 간단한 데이터베이스 백업 시스템을 만드는 것도 가능합니다. 스케줄러에 등록해 하루 단위로 이렇게 실행해 두면,

C:\temp> type c:\temp\db.settings.txt
192.168.100.50,1433
...[DB계정]...
...[비밀번호]...
TESTDB

C:\temp> ExportBacpac "c:\temp\db.settings.txt" c:\temp

192.168.100.50,1433 DB 서버에 접속해 "TESTDB" 데이터베이스를 "c:\temp\TESTDB_2024_01_05.bacpac"과 같은 식의 파일명으로 백업할 수 있습니다.

복원도 이와 유사하게 명령을 내리면 됩니다.

c:\temp> ImportBacpac.exe "C:\temp\TESTDB_2024_01_05.bacpac" TESTDB

그럼 ImportBacpac을 실행하는 localhost에 Windows 통합 계정으로 로그인을 해 TESTDB_2024_01_05.bacpac 파일의 내용을 새롭게 TESTDB 데이터베이스로 복원을 합니다.

간단하죠? ^^ 좀 더 응용해서 위의 과정을 합치는 배치 파일을 만들어 두면,

for /f %%i in ('"c:\temp\ExportBacpac.exe" "C:\temp\db.settings.txt" C:\temp') do set CREATED_FILE_PATH=%%i

echo %CREATED_FILE_PATH% Created!

"c:\temp\ImportBacpac.exe" "%CREATED_FILE_PATH%" TESTDB

매일 특정 DB를 로컬 측으로 동기화하도록 만들 수 있습니다.

(첨부 파일은 이 글의 예제 코드를 포함합니다. 크기를 줄이기 위해 참조한 DLL은 누락시켰습니다.)




[이 글에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]







[최초 등록일: ]
[최종 수정일: 1/21/2024]

Creative Commons License
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.
by SeongTae Jeong, mailto:techsharer at outlook.com

비밀번호

댓글 작성자
 




... [16]  17  18  19  20  21  22  23  24  25  26  27  28  29  30  ...
NoWriterDateCnt.TitleFile(s)
13241정성태2/3/20234003디버깅 기술: 188. ASP.NET Web Application (.NET Framework) 프로젝트의 숨겨진 예외 - System.IO.FileNotFoundException
13240정성태2/1/20234166디버깅 기술: 187. ASP.NET Web Application (.NET Framework) 프로젝트의 숨겨진 예외 - System.Web.HttpException
13239정성태2/1/20233848디버깅 기술: 186. C# - CacheDependency의 숨겨진 예외 - System.Web.HttpException
13238정성태1/31/20235972.NET Framework: 2092. IIS 웹 사이트를 TLS 1.2 또는 TLS 1.3 프로토콜로만 운영하는 방법
13237정성태1/30/20235648.NET Framework: 2091. C# - 웹 사이트가 어떤 버전의 TLS/SSL을 지원하는지 확인하는 방법
13236정성태1/29/20235171개발 환경 구성: 663. openssl을 이용해 인트라넷 IIS 사이트의 SSL 인증서 생성
13235정성태1/29/20234773개발 환경 구성: 662. openssl - 윈도우 환경의 명령행에서 SAN 적용하는 방법
13234정성태1/28/20235884개발 환경 구성: 661. dnSpy를 이용해 소스 코드가 없는 .NET 어셈블리의 코드를 변경하는 방법 [1]
13233정성태1/28/20237271오류 유형: 840. C# - WebClient로 https 호출 시 "The request was aborted: Could not create SSL/TLS secure channel" 예외 발생
13232정성태1/27/20234947스크립트: 43. uwsgi의 --processes와 --threads 옵션
13231정성태1/27/20233958오류 유형: 839. python - TypeError: '...' object is not callable
13230정성태1/26/20234329개발 환경 구성: 660. WSL 2 내부로부터 호스트 측의 네트워크로 UDP 데이터가 1개의 패킷으로만 제한되는 문제
13229정성태1/25/20235338.NET Framework: 2090. C# - UDP Datagram의 최대 크기
13228정성태1/24/20235458.NET Framework: 2089. C# - WMI 논리 디스크가 속한 물리 디스크의 정보를 얻는 방법 [2]파일 다운로드1
13227정성태1/23/20235131개발 환경 구성: 659. Windows - IP MTU 값을 바꿀 수 있을까요? [1]
13226정성태1/23/20234810.NET Framework: 2088. .NET 5부터 지원하는 GetRawSocketOption 사용 시 주의할 점
13225정성태1/21/20234012개발 환경 구성: 658. Windows에서 실행 중인 소켓 서버를 다른 PC 또는 WSL에서 접속할 수 없는 경우
13224정성태1/21/20234444Windows: 221. Windows - Private/Public/Domain이 아닌 네트워크 어댑터 단위로 방화벽을 on/off하는 방법
13223정성태1/20/20234609오류 유형: 838. RDP 연결 오류 - The two computers couldn't connect in the amount of time allotted
13222정성태1/20/20234303개발 환경 구성: 657. WSL - DockerDesktop.vhdx 파일 위치를 옮기는 방법
13221정성태1/19/20234470Linux: 57. C# - 리눅스 프로세스 메모리 정보파일 다운로드1
13220정성태1/19/20234574오류 유형: 837. NETSDK1045 The current .NET SDK does not support targeting .NET ...
13219정성태1/18/20234190Windows: 220. 네트워크의 인터넷 접속 가능 여부에 대한 판단 기준
13218정성태1/17/20234087VS.NET IDE: 178. Visual Studio 17.5 (Preview 2) - 포트 터널링을 이용한 웹 응용 프로그램의 외부 접근 허용
13217정성태1/13/20234704디버깅 기술: 185. windbg - 64비트 운영체제에서 작업 관리자로 뜬 32비트 프로세스의 덤프를 sos로 디버깅하는 방법
13216정성태1/12/20234958디버깅 기술: 184. windbg - 32비트 프로세스의 메모리 덤프인 경우 !peb 명령어로 나타나지 않는 환경 변수
... [16]  17  18  19  20  21  22  23  24  25  26  27  28  29  30  ...