Microsoft MVP성태의 닷넷 이야기
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
(연관된 글이 1개 있습니다.)

C# - 닷넷 응용 프로그램에서 DB2 Express-C 데이터베이스 사용 (2)

지난번에는 서버 구성에 대해서 이야기했었는데요.

C# - 닷넷 응용 프로그램에서 DB2 Express-C 데이터베이스 사용 (1)
; https://www.sysnet.pe.kr/2/0/1407

MySQL 테스트 때와 동일하게 mytestdb라는 이름의 테스트 DB를 구성하고 테이블을 다음과 같이 구성했습니다.

db2_ids_clnt_1.png

이에 대한 db2 연결 문자열은 평범합니다.

Server=testdbserver:50000;Database=mytestdb;UID=db2test;PWD=db2test@2008;

여기서 UID가 중요한데, 테이블의 기본 적용될 스키마 명이 됩니다. 예를 들어, SQL 쿼리를 다음과 같이 지정하면,

SELECT * FROM mytable

DB2는 연결 문자열의 UID를 스키마 명으로 해서 "DB2TEST.MYTABLE"을 찾습니다. 따라서, 만약 "My"라는 이름의 스키마에 MYTABLE 테이블을 생성해 놓았다면, UID와 다르므로 이런 경우에는 명시적으로 "MY.MYTABLE"이라고 해야 합니다.

테스트를 위한 서버 구성은 이걸로 끝!




이제 닷넷에서 DB2 서버를 접속하기 위한 ADO.NET Data Provider가 있어야 합니다. 다행히 IBM에서는 "IBM Data Server Driver Package"에 ADO.NET 데이터 제공자를 포함해서 배포하고 있으며 다음의 경로에서 다운로드할 수 있습니다.

Data Server Client and driver packages 
; http://www.ibm.com/support/docview.wss?rs=4020&uid=swg21385217

IBM Data Server Driver Package (DS Driver)?
; https://www.ibm.com/services/forms/preLogin.do?source=swg-idsdpds

제 경우에는 위의 URL을 통해 "IBM Data Server Driver Package (Windows AMD64 and Intel EM64T) 10.1" 항목을 다운로드 받았습니다.

설치 후, IBM Data Server Driver Package에 대한 Fix packs를 다음의 경로에서 다운로드 받을 수 있습니다.

IBM Data Server Client Packages fix pack - DSClients-ntx64-dsdriver-10.1.200.238-FP002
- v10.1fp2_ntx64_dsdriver_ALL_LANG.exe (90.76 MB)
; http://www.ibm.com/support/docview.wss?uid=swg27016878

"IBM Data Server Driver Package"를 64비트로 다운로드 받았으므로 Fix Pack도 윈도우 64비트로 "IBM Data Server Driver Package (Windows/x86-64 64 bit) V10.1 Fix Pack 2" 항목을 다운로드 받습니다. (제 경우에는 간단한 테스트 목적이므로 Fix Pack 설치는 안했습니다.)

다음은 IBM Data Server Provider for .NET을 위한 IBM 측의 공식 웹 문서입니다.

ADO.NET application development
; http://pic.dhe.ibm.com/infocenter/db2luw/v9r7/index.jsp?topic=%2Fcom.ibm.swg.im.dbclient.adonet.doc%2Fdoc%2Fc0010960.html

IBM Data Server Driver Package를 설치하면 GAC에 관련 DLL들이 설치되는데 기본적인 ADO.NET Provider의 이름은 IBM.Data.DB2.dll이므로 이것을 참조해 다음의 코드를 만들 수 있습니다.

using (DB2Connection connection = new DB2Connection())
{
    connection.ConnectionString = "Server=testdbserver:50000;Database=mytestdb;UID=db2test;PWD=db2test@2008;";
    connection.Open();

    // Create
    DB2Command insertCommand = new DB2Command();
    insertCommand.Connection = connection;
    insertCommand.CommandText = "INSERT INTO mytable(id, NAME, age, DESCRIPTION) VALUES (@id, @NAME, @age, @DESCRIPTION)";

    insertCommand.Parameters.Add("@id", DB2Type.Integer);
    insertCommand.Parameters.Add("@NAME", DB2Type.VarChar, 50);
    insertCommand.Parameters.Add("@age", DB2Type.Integer);
    insertCommand.Parameters.Add("@DESCRIPTION", DB2Type.VarChar, 150);

    string nameValue = "Name" + Guid.NewGuid().ToString();
    insertCommand.Parameters[0].Value = (int)DateTime.Now.Ticks;
    insertCommand.Parameters[1].Value = nameValue;
    insertCommand.Parameters[2].Value = 10;
    insertCommand.Parameters[3].Value = nameValue + "_Description";

    int affected = insertCommand.ExecuteNonQuery();
    Console.WriteLine("# of affected row: " + affected);

    // Update
    DB2Command updateCommand = new DB2Command();
    updateCommand.Connection = connection;
    updateCommand.CommandText = "UPDATE mytable SET DESCRIPTION=@DESCRIPTION WHERE NAME=@NAME";

    updateCommand.Parameters.Add("@NAME", DB2Type.VarChar, 50);
    updateCommand.Parameters.Add("@DESCRIPTION", DB2Type.VarChar, 150);

    updateCommand.Parameters[0].Value = nameValue;
    updateCommand.Parameters[1].Value = nameValue + "_Description2";

    affected = updateCommand.ExecuteNonQuery();
    Console.WriteLine("# of affected row: " + affected);

    // Select - ExecuteScalar
    DB2Command selectCommand = new DB2Command();
    selectCommand.Connection = connection;
    selectCommand.CommandText = "SELECT count(*) FROM mytable";

    object result = selectCommand.ExecuteScalar();
    Console.WriteLine("# of records: " + result);

    // Select - DataTable
    DataSet ds = new DataSet();
    DB2DataAdapter da = new DB2DataAdapter("SELECT * FROM mytable", connection);
    da.Fill(ds, "mytable");

    DataTable dt = ds.Tables["mytable"];
    foreach (DataRow dr in dt.Rows)
    {
        Console.WriteLine(string.Format("Name = {0}, Desc = {1}", dr["NAME"], dr["DESCRIPTION"]));
    }

    // Delete
    DB2Command deleteCommand = new DB2Command();
    deleteCommand.Connection = connection;
    deleteCommand.CommandText = "DELETE FROM mytable WHERE NAME=@NAME";

    deleteCommand.Parameters.Add("@NAME", DB2Type.VarChar, 50);
    deleteCommand.Parameters[0].Value = nameValue;

    affected = deleteCommand.ExecuteNonQuery();
    Console.WriteLine("# of affected row: " + affected);
}

보시는 것처럼 MySQL 예제와 거의 동일합니다.

참고로, IBM.Data.DB2.dll 파일은 MySQL의 경우와는 달리 완전한 형식의 데이터 제공자는 아닙니다. 내부에서 Native 모듈을 필요로 하므로 AnyCPU의 편리함을 누릴 수는 없고 닷넷 응용 프로그램을 x86, x64로 나누어야 합니다. 게다가, .NET 2.0과 .NET 4.0 모듈이 분리되어 있습니다. 이 때문에 "IBM Data Server Driver Package"를 설치하면 다음의 경로에 각각의 모듈을 분리해서 제공합니다.

.NET 2.0용 x64: C:\Program Files\IBM\IBM DATA SERVER DRIVER\bin\netf20
.NET 2.0용 x86: C:\Program Files\IBM\IBM DATA SERVER DRIVER\bin\netf20_32
.NET 4.0용 x64: C:\Program Files\IBM\IBM DATA SERVER DRIVER\bin\netf40
.NET 4.0용 x86: C:\Program Files\IBM\IBM DATA SERVER DRIVER\bin\netf40_32




그런데, IBM Data Server Driver Package를 고객 PC에 함께 배포해야 한다는 것이 그다지 좋은 방법은 아닙니다. 혹시 "IBM Data Server Driver Package" 설치 없이 XCopy 식의 배포가 되진 않을까요? 그래서 이래저래 해보니 ^^ 가능하다는 것을 알았습니다.

그런데, 약간 제약이 있습니다. 예를 들어, DB2를 사용하는 test.exe라는 파일을 다른 컴퓨터에 복사한다고 가정해 보겠습니다. 그럼, 다음과 같은 식으로 배포해 줘야 합니다.

  1. C:\Program Files\IBM\IBM DATA SERVER DRIVER\bin 폴더의 내용을 모두 c:\temp\bin에 복사 (반드시 bin 이름이어야 함.)
  2. c:\temp\bin 폴더에 test.exe와 IBM.Data.DB2.dll 파일을 복사

특이하죠. ^^ 반드시 test.exe와 DB2 구성 요소들이 들어가는 폴더의 이름이 bin이어야 합니다. 안 그러면 오류가 발생합니다. 어찌 보면, 큰 제약은 아닙니다. 다행히 Web Application의 경우 \bin 폴더 이름이기 때문에 사용에 지장은 없습니다.

첨부된 프로젝트는 제가 구성한 Console, Web 예제입니다.




IBM Data Server Driver Package (ibm_data_server_driver_package_win64_v10.1.exe)를 윈도우 8및 서버 2012에 설치할 때 다음과 같은 오류가 발생할 수 있습니다.

설치 마법사 완료

이 컴퓨터에 IBM Data Server Driver Package을(를) 설치하는 중에 심각한 오류가 발생했습니다. 설치를 계속할 수 없습니다. 설치 로그는 C:\Users\[사용자계정]\DOCUME~1\DB2LOG\dsdriver_log-[날짜].log 에 있습니다.

사용자 시스템이 수정되지 않았습니다.

설치 마법사를 종료하려면 완료를 클릭하십시오.

로그를 봐도 별다른 원인을 찾아낼 수 없었습니다.

=== 기록 시작: 2013-01-24  16:27:06 ===
MSI (c) (0C:28) [16:27:06:396]: Note: 1: 1708 
MSI (c) (0C:28) [16:27:06:396]: Transforming table Error.

MSI (c) (0C:28) [16:27:06:412]: Transforming table Error.

MSI (c) (0C:28) [16:27:06:412]: 제품: IBM Data Server Driver Package - IBMDBCL1 - 설치를 실패했습니다.

MSI (c) (0C:28) [16:27:06:427]: Windows Installer에서 제품을 설치했습니다. 제품 이름: IBM Data Server Driver Package - IBMDBCL1. 제품 버전: 10.1.0.872. 제품 언어: 1042. 제조 업체: 회사명. 설치 성공 또는 오류 상태: 1603.

MSI (c) (0C:28) [16:27:06:521]: Grabbed execution mutex.
MSI (c) (0C:28) [16:27:06:521]: Cleaning up uninstalled install packages, if any exist
MSI (c) (0C:28) [16:27:06:521]: MainEngineThread is returning 1603
=== Verbose logging stopped: 2013-01-24  16:27:06 ===

원인은 정확히 알 수 없었습니다. 아직은 8과 2012를 지원하지 않는 것 같기도 한데... 이건 좀 기다려야 할 것 같습니다. ^^ 다행히 XCopy 배포가 가능하기 때문에 크게 문제되지는 않습니다.




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

[연관 글]






[최초 등록일: ]
[최종 수정일: 6/27/2021]

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

비밀번호

댓글 작성자
 



2017-07-28 04시14분
[sonson] 정성태님 아티클 잘보고 갑니다. ^^
[guest]

[1]  2  3  4  5  6  7  8  9  10  11  12  13  14  15  ...
NoWriterDateCnt.TitleFile(s)
13606정성태4/24/202498닷넷: 2247. C# - tensorflow 연동 (MNIST 예제)파일 다운로드1
13605정성태4/23/2024331닷넷: 2246. C# - Python.NET을 이용한 파이썬 소스코드 연동파일 다운로드1
13604정성태4/22/2024353오류 유형: 901. Visual Studio - Unable to set the next statement. Set next statement cannot be used in '[Exception]' call stack frames.
13603정성태4/21/2024626닷넷: 2245. C# - IronPython을 이용한 파이썬 소스코드 연동파일 다운로드1
13602정성태4/20/2024799닷넷: 2244. C# - PCM 오디오 데이터를 연속(Streaming) 재생 (Windows Multimedia)파일 다운로드1
13601정성태4/19/2024839닷넷: 2243. C# - PCM 사운드 재생(NAudio)파일 다운로드1
13600정성태4/18/2024848닷넷: 2242. C# - 관리 스레드와 비관리 스레드
13599정성태4/17/2024863닷넷: 2241. C# - WAV 파일의 PCM 사운드 재생(Windows Multimedia)파일 다운로드1
13598정성태4/16/2024885닷넷: 2240. C# - WAV 파일 포맷 + LIST 헤더파일 다운로드2
13597정성태4/15/2024868닷넷: 2239. C# - WAV 파일의 PCM 데이터 생성 및 출력파일 다운로드1
13596정성태4/14/20241052닷넷: 2238. C# - WAV 기본 파일 포맷파일 다운로드1
13595정성태4/13/20241050닷넷: 2237. C# - Audio 장치 열기 (Windows Multimedia, NAudio)파일 다운로드1
13594정성태4/12/20241068닷넷: 2236. C# - Audio 장치 열람 (Windows Multimedia, NAudio)파일 다운로드1
13593정성태4/8/20241079닷넷: 2235. MSBuild - AccelerateBuildsInVisualStudio 옵션
13592정성태4/2/20241218C/C++: 165. CLion으로 만든 Rust Win32 DLL을 C#과 연동
13591정성태4/2/20241196닷넷: 2234. C# - WPF 응용 프로그램에 Blazor App 통합파일 다운로드1
13590정성태3/31/20241078Linux: 70. Python - uwsgi 응용 프로그램이 k8s 환경에서 OOM 발생하는 문제
13589정성태3/29/20241150닷넷: 2233. C# - 프로세스 CPU 사용량을 나타내는 성능 카운터와 Win32 API파일 다운로드1
13588정성태3/28/20241263닷넷: 2232. C# - Unity + 닷넷 App(WinForms/WPF) 간의 Named Pipe 통신 [2]파일 다운로드1
13587정성태3/27/20241168오류 유형: 900. Windows Update 오류 - 8024402C, 80070643
13586정성태3/27/20241330Windows: 263. Windows - 복구 파티션(Recovery Partition) 용량을 늘리는 방법
13585정성태3/26/20241112Windows: 262. PerformanceCounter의 InstanceName에 pid를 추가한 "Process V2"
13584정성태3/26/20241063개발 환경 구성: 708. Unity3D - C# Windows Forms / WPF Application에 통합하는 방법파일 다운로드1
13583정성태3/25/20241302Windows: 261. CPU Utilization이 100% 넘는 경우를 성능 카운터로 확인하는 방법
13582정성태3/19/20241559Windows: 260. CPU 사용률을 나타내는 2가지 수치 - 사용량(Usage)과 활용률(Utilization)파일 다운로드1
[1]  2  3  4  5  6  7  8  9  10  11  12  13  14  15  ...