Microsoft MVP성태의 닷넷 이야기
.NET Framework: 2000. C# - 닷넷 응용 프로그램에서 Informix DB 사용 방법 [링크 복사], [링크+제목 복사],
조회: 14752
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일

C# - 닷넷 응용 프로그램에서 Informix DB 사용 방법

이를 위해 우선, Informix DB 서버가 필요한데요, 간단하게 docker를 이용해 해결할 수 있습니다. 따라서, 다음의 글에 따라 설치를 해주시고,

Informix 데이터베이스 docker 환경 구성
; https://www.sysnet.pe.kr/2/0/13041

그다음, Informix Client SDK를 설치합니다.

Informix Client Software Development Kit (Client SDK) and Informix Connect System Requirements
; https://www.ibm.com/support/pages/informix-client-software-development-kit-client-sdk-and-informix-connect-system-requirements

Where to download Informix Client SDK
; https://www.ibm.com/support/pages/where-download-informix-client-sdk

보니까, 공식적으로는 Trial 형식으로만 다운로드가 가능한 것 같습니다. 다행히 제 경우에는 ^^ 설치 파일을 가지고 있어서 installclientsdk.exe를 실행해 설치했습니다. 그리고 .NET Framework과 .NET Core의 DLL은 각각 다음의 위치에서 구할 수 있습니다.

[닷넷 프레임워크]
C:\Program Files\IBM Informix Client-SDK\bin\netf40\IBM.Data.Informix.dll

[닷넷 코어]
C:\Program Files\IBM Informix Client-SDK\bin\Informix.Net.Core.dll 

일례로 .NET 5 프로젝트라면 Informix.Net.Core.dll을 참조 추가해 진행하면 됩니다. 이와 함께 참고할 수 있는 코드는 다음의 경로에서 예제를 찾을 수 있습니다.

C:\Program Files\IBM Informix Client-SDK\demo

그나저나... 이유는 알 수 없지만, 저번 docker 컨테이너도 그렇고 되게 불친절한 개발사인 것 같습니다. 쓰라고 권유하는 것이 아닌, 뭔가 좋은 걸 숨기려고(?) 하는 듯한 ^^; 정책 같아 보입니다.




코드 실행에 앞서 우선 환경 설정을 해야 합니다. 레지스트리에 Informix 데이터베이스 접속을 위한 환경 정보를 구성해야 하는데요, 이를 위해 setnet32.exe를 이용하시면 됩니다.

C:\Program Files\IBM Informix Client-SDK\bin\setnet32.exe

docker로 기본 실행한 상태라면 아래와 같이 설정하고,

dotnet_informix_connect_1.png

"Apply" 버튼을 누릅니다. 그럼, "HKEY_LOCAL_MACHINE\SOFTWARE\Informix\SqlHosts" 경로에 위의 설정을 담은 "informix" 키가 생성됩니다.

이렇게 설정을 마치면, 이제부터 DB 연결 문자열을 다음과 같이 구성하면 됩니다.

string connectionString = "Server=informix; User ID=informix; Password=in4mix";

일반적으로, DB 연결 문자열에서 "Server"는 DB가 설치된 IP 또는 DNS 이름이 와야 하는데요, Informix의 경우에는 위에서 보는 바와 같이 레지스트리에 설정한 키 이름이어야 합니다. (개인적으로 Informix에서 가장 헷갈린 부분이 저것이었습니다. ^^;)




이후 코드 작성은 일반적인 SqlClient 사용하듯이 만들면 됩니다. 단지, parameterized query에서 "@" + "이름" 대신 순서를 가진 "?" 문자로 대체해야 합니다. 따라서 대략 다음과 같은 식으로 예제 코드를 작성할 수 있습니다.

using Informix.Net.Core;
using System;
using System.Data;

namespace ConsoleApp1
{
    internal class Program
    {
        static void Main(string[] args)
        {
            string connectionString = "Server=informix; User ID=informix; Password=in4mix";

            CreateSampleDB(connectionString);

            TouchDatabase(connectionString);
        }

        private static void TouchDatabase(string connectionString)
        {
            using (IfxConnection connection = new IfxConnection($"{connectionString}; Database=mydb"))
            {
                connection.ConnectionString = connectionString;
                connection.Open();

                // Create
                IfxCommand insertCommand = new IfxCommand();
                insertCommand.Connection = connection;
                insertCommand.CommandText = "insert into mytable(name, age) values (?, ?);";
                insertCommand.Parameters.Add("@name", IfxType.VarChar, 50);
                insertCommand.Parameters.Add("@age", IfxType.Integer);

                string nameValue = "Name" + Guid.NewGuid().ToString();
                insertCommand.Parameters[0].Value = nameValue;
                insertCommand.Parameters[1].Value = 10;

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

                // Update
                IfxCommand updateCommand = new IfxCommand();
                updateCommand.Connection = connection;
                updateCommand.CommandText = "UPDATE mytable SET age=? WHERE name=?";

                updateCommand.Parameters.Add("@age", IfxType.Integer);
                updateCommand.Parameters.Add("@name", IfxType.VarChar, 50);

                updateCommand.Parameters[0].Value = 6;
                updateCommand.Parameters[1].Value = nameValue;

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

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

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

                // Select - DataTable
                DataSet ds = new DataSet();
                IfxDataAdapter da = new IfxDataAdapter("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["age"]));
                }

                // Delete
                IfxCommand deleteCommand = new IfxCommand();
                deleteCommand.Connection = connection;
                deleteCommand.CommandText = "DELETE FROM mytable WHERE name=?";

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

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

        private static void CreateSampleDB(string connectionString)
        {
            IfxConnection conn = new IfxConnection(connectionString);
            conn.Open();

            IfxCommand cmd = new IfxCommand("CREATE DATABASE IF NOT EXISTS mydb");
            cmd.Connection = conn;
            cmd.ExecuteNonQuery();

            cmd.CommandText = @"CREATE TABLE IF NOT EXISTS mytable
               (
                   id  SERIAL NOT NULL PRIMARY KEY,
                   name    VARCHAR(50),
                   age      INTEGER
               );";
            cmd.ExecuteNonQuery();

            conn.Close();
        }
    }
}




그런데, 혹시 installclientsdk.exe를 설치하지 않은 환경에서도 실행하는 것이 가능할까요?

아쉽게도 완전한 Managed 드라이버가 아니기 때문에, 매우 복잡한 작업이 필요합니다. 일단, 제가 테스트한 바로는, 이 글에서 예로 든 코드를 실행하기 위한 최소한의 조건을 다음과 같이 갖춰야 합니다.

1) EXE 실행 파일의 경로에 다음의 DLL들도 함께 배포

iclit09b.dll
    iregt07b.dll
        irrgt09a.dll
    igl4n304.dll
    irclt09b.dll
igo4n304.dll

테스트해 보면, native dll을 찾는 위치는 exe 파일 또는 환경 변수 PATH에 지정된 경로에만 있으면 됩니다. 이로 인해, Visual Studio에서 ASP.NET Core 프로젝트로 실행하는 경우라면 약간의 문제가 발생합니다. 위에 나열한 DLL을 프로젝트에 추가해 함께 배포를 해도, iisexpress.exe나 w3wp.exe가 위치한 경로와는 다르므로 저 DLL을 찾지 못하게 됩니다. 따라서 그런 경우에는, 프로젝트 속성 창의 "Open debug launch profiles UI" 창을 띄워 해당하는 응용 프로그램에 대해 "Environment variables"를 이런 식으로,

ASPNETCORE_ENVIRONMENT=Development,PATH=%PATH%;C:\test\aspnetcore_prj\bin\Debug\net5.0

설정해 줘야 합니다.

그건 그렇고, 저걸 실 서버에 배포하는 경우에는, 어쩔 수 없습니다. 간편하게는 그냥 실 서버에도 installclientsdk.exe를 실행하든가, 아니면 별도의 디렉터리를 만들어 위의 DLL들을 복사 후 시스템 전역으로 PATH 환경 변수에 그 경로를 추가해야 합니다.

2) INFORMIXDIR 레지스트리 설정

뿐만 아니라, 아래와 같이 레지스트리 설정을 추가하고, 해당 "INFORMIXDIR"에 지정한 경로에는 informix native DLL을 포함한 파일들이 위치하고 있어야 합니다.

Windows Registry Editor Version 5.00

[HKEY_LOCAL_MACHINE\SOFTWARE\Informix]

[HKEY_LOCAL_MACHINE\SOFTWARE\Informix\Environment]
"INFORMIXDIR"="C:\\temp\\informix"

3) SqlHosts 레지스트리 설정

마지막으로, (이전에는 setnet32.exe로 설정했던) 연결 문자열에 지정하는 레지스트리 설정도 추가되어야 합니다.

Windows Registry Editor Version 5.00

[HKEY_LOCAL_MACHINE\SOFTWARE\Informix\SqlHosts\informix]
"HOST"="127.0.0.1"
"SERVICE"="9088"
"PROTOCOL"="onsoctcp"

복잡하긴 한데, 일단 위와 같은 구성으로만 하면 동작은 합니다. ^^; 그런데... 정말 요즘 같은 세상에 저렇게 native dll을 필요로 하는 것도 그렇고, 여러모로 참... 불친절한 라이브러리입니다. ^^;




이런 식으로 native dll을 유지하는 것 외에, 이 라이브러리가 얼마나 무신경한지 알 수 있는 한 가지 특징이 더 있습니다. 뭐냐면, Informix.Net.Core.dll은 async/await을 위한 비동기 메서드를 제공하지 않고 있습니다. 하지만, 그래도 다음과 같은 식으로 비동기 메서드를 호출할 수는 있는데요,

using (IfxConnection connection = new IfxConnection($"{connectionString}; Database=mydb"))
{
    connection.ConnectionString = connectionString;
    await connection.OpenAsync();
}

이것은, IfxConnection 타입에서 제공하는 메서드가 아닌, System.Data.Common의 DbConnection 수준에서 제공하는 기본 OpenAsync 구현에 불과합니다. 이에 대해서는 아래에서 이미 설명했으니,

C# - 동기 방식이면서 비동기 메서드처럼 구현한 사례
; https://www.sysnet.pe.kr/2/0/11431

참고하시고, 따라서 await 호출이지만 결국 async 인터페이스만 맞춘 것일 뿐, 일반적인 Open 동기 메서드를 호출한 것과 완전히 같게 동작합니다.

그러니까, 딱히 비동기 유형에 대한 구현을 아직도 하고 있지 않은 것입니다.

(첨부 파일은, 설치 작업 없이 Informix .NET Core 라이브러리를 사용할 수 있는 최소한의 예제 프로젝트를 포함합니다.)




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







[최초 등록일: ]
[최종 수정일: 5/3/2022]

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

비밀번호

댓글 작성자
 




... 76  77  78  79  80  81  82  83  84  [85]  86  87  88  89  90  ...
NoWriterDateCnt.TitleFile(s)
11811정성태2/11/201920947오류 유형: 510. 서버 운영체제에 NVIDIA GeForce Experience 실행 시 wlanapi.dll 누락 문제
11810정성태2/11/201918538.NET Framework: 808. .NET Profiler - GAC 모듈에서 GAC 비-등록 모듈을 참조하는 경우의 문제
11809정성태2/11/201920759.NET Framework: 807. ClrMD를 이용해 메모리 덤프 파일로부터 특정 인스턴스를 참조하고 있는 소유자 확인
11808정성태2/8/201922073디버깅 기술: 123. windbg - 닷넷 응용 프로그램의 메모리 누수 분석
11807정성태1/29/201919976Windows: 156. 가상 디스크의 용량을 복구 파티션으로 인해 늘리지 못하는 경우 [4]
11806정성태1/29/201919607디버깅 기술: 122. windbg - 덤프 파일로부터 PID와 환경 변수 등의 정보를 구하는 방법
11805정성태1/28/201921786.NET Framework: 806. C# - int []와 object []의 차이로 이해하는 제네릭의 필요성 [4]파일 다운로드1
11804정성태1/24/201919638Windows: 155. diskpart - remove letter 이후 재부팅 시 다시 드라이브 문자가 할당되는 경우
11803정성태1/10/201918504디버깅 기술: 121. windbg - 닷넷 Finalizer 스레드가 멈춰있는 현상
11802정성태1/7/201920214.NET Framework: 805. 두 개의 윈도우를 각각 실행하는 방법(Windows Forms, WPF)파일 다운로드1
11801정성태1/1/201921483개발 환경 구성: 427. Netsh의 네트워크 모니터링 기능 [3]
11800정성태12/28/201820601오류 유형: 509. WCF 호출 오류 메시지 - System.ServiceModel.CommunicationException: Internal Server Error
11799정성태12/19/201822356.NET Framework: 804. WPF(또는 WinForm)에서 UWP UI 구성 요소 사용하는 방법 [3]파일 다운로드1
11798정성태12/19/201821208개발 환경 구성: 426. vcpkg - "Building vcpkg.exe failed. Please ensure you have installed Visual Studio with the Desktop C++ workload and the Windows SDK for Desktop C++"
11797정성태12/19/201817188개발 환경 구성: 425. vcpkg - CMake Error: Problem with archive_write_header(): Can't create '' 빌드 오류
11796정성태12/19/201817526개발 환경 구성: 424. vcpkg - "File does not have expected hash" 오류를 무시하는 방법
11795정성태12/19/201820749Windows: 154. PowerShell - Zone 별로 DNS 레코드 유형 정보 조회 [1]
11794정성태12/16/201816868오류 유형: 508. Get-AzureWebsite : Request to a downlevel service failed.
11793정성태12/16/201819379개발 환경 구성: 423. NuGet 패키지 제작 - Native와 Managed DLL을 분리하는 방법 [1]
11792정성태12/11/201819175Graphics: 34. .NET으로 구현하는 OpenGL (11) - Per-Pixel Lighting파일 다운로드1
11791정성태12/11/201819187VS.NET IDE: 130. C/C++ 프로젝트의 시작 프로그램으로 .NET Core EXE를 지정하는 경우 닷넷 디버깅이 안 되는 문제 [1]
11790정성태12/11/201817645오류 유형: 507. Could not save daemon configuration to C:\ProgramData\Docker\config\daemon.json: Access to the path 'C:\ProgramData\Docker\config' is denied.
11789정성태12/10/201831276Windows: 153. C# - USB 장치의 연결 및 해제 알림을 위한 WM_DEVICECHANGE 메시지 처리 [2]파일 다운로드2
11788정성태12/4/201817557오류 유형: 506. SqlClient - Value was either too large or too small for an Int32.Couldn't store <2151292191> in ... Column
11787정성태11/29/201821714Graphics: 33. .NET으로 구현하는 OpenGL (9), (10) - OBJ File Format, Loading 3D Models파일 다운로드1
11786정성태11/29/201818688오류 유형: 505. OpenGL.NET 예제 실행 시 "Managed Debugging Assistant 'CallbackOnCollectedDelegate'" 예외 발생
... 76  77  78  79  80  81  82  83  84  [85]  86  87  88  89  90  ...