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

ODP.NET의 완전한 닷넷 버전 Oracle ODP.NET, Managed Driver

반가운 소식입니다. ^^

그동안 Native와 Managed가 섞인 체로 오라클 DB를 사용할 수 있게만 해주는 ODP.NET이 배포되고 있었는데요. 어느샌가 완전한 .NET 버전의 ODP.NET을 배포해주고 있었군요. ^^

Introduction to Building ODP.NET, Managed Driver Applications
; http://www.oracle.com/webfolder/technetwork/tutorials/obe/db/12c/r1/appdev/dotnet/Web_version_Fully_Managed_ODPnet_OBE/odpnetmngdrv.html

오직 .NET 코드로만 작성되었고 AnyCPU 유형으로 제작된 것이라 배포도 간편합니다. Nuget 설치도 지원해서

Official Oracle ODP.NET, Managed Driver 
; https://www.nuget.org/packages/Oracle.ManagedDataAccess/

비주얼 스튜디오의 Nuget 콘솔 창을 이용해 다음과 같이 간편하게 설치할 수 있습니다.

PM> Install-Package Oracle.ManagedDataAccess 
Attempting to gather dependencies information for package 'Oracle.ManagedDataAccess.12.1.2400' with respect to project 'ConsoleApplication1', targeting '.NETFramework,Version=v4.0'
Attempting to resolve dependencies for package 'Oracle.ManagedDataAccess.12.1.2400' with DependencyBehavior 'Lowest'
Resolving actions to install package 'Oracle.ManagedDataAccess.12.1.2400'
Resolved actions to install package 'Oracle.ManagedDataAccess.12.1.2400'
Adding package 'Oracle.ManagedDataAccess.12.1.2400' to folder 'C:\...\ConsoleApplication1\packages'
Added package 'Oracle.ManagedDataAccess.12.1.2400' to folder 'C:\...\ConsoleApplication1\packages'
Added package 'Oracle.ManagedDataAccess.12.1.2400' to 'packages.config'
Successfully installed 'Oracle.ManagedDataAccess 12.1.2400' to ConsoleApplication1

아쉬운 점이 있다면, Oracle.ManagedDataAccess.dll이 .NET 4.0 대상으로 빌드되었기 때문에 .NET 3.5 이하의 응용 프로그램에서는 사용할 수 없습니다. (사실, 4.0 나온지 꽤 되었기 때문에 단점이라고 볼 수는 없겠습니다.)

참고로, 3.5 응용 프로그램에 설치하려고 하면 다음과 같이 오류가 발생합니다.

PM> Install-Package Oracle.ManagedDataAccess 
Attempting to gather dependencies information for package 'Oracle.ManagedDataAccess.12.1.2400' with respect to project 'ConsoleApplication1', targeting '.NETFramework,Version=v3.5'
Attempting to resolve dependencies for package 'Oracle.ManagedDataAccess.12.1.2400' with DependencyBehavior 'Lowest'
Resolving actions to install package 'Oracle.ManagedDataAccess.12.1.2400'
Resolved actions to install package 'Oracle.ManagedDataAccess.12.1.2400'
Install failed. Rolling back...
Package 'Oracle.ManagedDataAccess.12.1.2400 : ' does not exist in project 'ConsoleApplication1'
Package 'Oracle.ManagedDataAccess.12.1.2400 : ' does not exist in folder 'C:\Users\SeongTae Jeong\Dropbox\articles\oracle_managed\ConsoleApplication1\packages'
Install-Package : Could not install package 'Oracle.ManagedDataAccess 12.1.2400'. You are trying to install this package into a project that 
targets '.NETFramework,Version=v3.5', but the package does not contain any assembly references or content files that are compatible with that
 framework. For more information, contact the package author.
At line:1 char:1
+ Install-Package Oracle.ManagedDataAccess
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [Install-Package], Exception
    + FullyQualifiedErrorId : NuGetCmdletUnhandledException,NuGet.PackageManagement.PowerShellCmdlets.InstallPackageCommand

이 외에, 모든 사용법은 기존의 ODP.NET과 동일합니다. 연결 문자열 및 기존 소스 코드는 단 하나도 수정할 일이 없고, 단지 네임스페이스만 "using Oracle.DataAccess.Client;"에서 "using Oracle.ManagedDataAccess.Client;"로 바꿔주면 됩니다.

using System;
using System.Data;

using Oracle.ManagedDataAccess.Client;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            string svrName = "...[Oracle 서버 주소]...";
            string userId = "...[사용자 id]...";
            string userPw = "...[사용자 암호]...";

            string connectionString = string.Format("Data Source=(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST={0})(PORT=1521))(CONNECT_DATA=(SERVICE_NAME=XE)));User Id={1};Password={2};", svrName, userId, userPw);

            //  또는, connectionString = string.Format("user id={0};password={1}; data source={2}:1521/XE", userId, userPw, svrName);
            
            using (OracleConnection oracleConnection =
                new OracleConnection(connectionString))
            {
                oracleConnection.Open();

                // Create
                OracleCommand insertCommand = new OracleCommand();
                insertCommand.Connection = oracleConnection;
                insertCommand.CommandText = "INSERT INTO mytable(id, NAME, age, DESCRIPTION) VALUES (:id, :NAME, :age, :DESCRIPTION)";

                insertCommand.Parameters.Add("id", OracleDbType.Int32);
                insertCommand.Parameters.Add("NAME", OracleDbType.Varchar2, 50);
                insertCommand.Parameters.Add("age", OracleDbType.Int32);
                insertCommand.Parameters.Add("DESCRIPTION", OracleDbType.Varchar2, 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
                OracleCommand updateCommand = new OracleCommand();
                updateCommand.Connection = oracleConnection;
                updateCommand.CommandText = "UPDATE mytable SET DESCRIPTION = :DESCRIPTION WHERE NAME = :NAME";

                updateCommand.Parameters.Add("NAME", OracleDbType.Varchar2, 50);
                updateCommand.Parameters.Add("DESCRIPTION", OracleDbType.Varchar2, 150);

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

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

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

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

                // Select - DataTable
                DataSet ds = new DataSet();
                OracleDataAdapter da = new OracleDataAdapter("SELECT * FROM mytable", oracleConnection);
                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
                OracleCommand deleteCommand = new OracleCommand();
                deleteCommand.Connection = oracleConnection;
                deleteCommand.CommandText = "DELETE FROM mytable WHERE NAME = :NAME";

                deleteCommand.Parameters.Add("NAME", OracleDbType.Varchar2, 50);
                deleteCommand.Parameters[0].Value = nameValue;

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

정리하면, 이제부터는 (약 4MB 짜리의) Oracle.ManagedDataAccess.dll 파일 하나만 참조해주시면 Oracle 데이터베이스와 접속할 수 있습니다.

한 가지 주의할 점이 있다면, "ODP.NET, Managed Driver" 중에서 Oracle.ManagedDataAccessDTC.dll, Oracle.ManagedDataAccessIOP.dll 2개의 구성 요소는 x86과 x64로 나뉘어져 있기 때문에 DTC 분산 트랜잭션을 사용하거나 Kerberos 인증 지원을 하는 경우는 .NET 응용 프로그램의 플랫폼 유형에 맞게 선택해 주어야 합니다. 그래도 뭐 이정도는 애교죠. ^^ 기존에는 플랫폼 별로 300 ~ 400MB에 달하는 ODAC 구성 요소를 함께 배포해주었어야 했던 것과 비교하면.

(첨부한 파일은 이 글의 예제 코드입니다.)




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

[연관 글]






[최초 등록일: ]
[최종 수정일: 7/9/2021]

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

비밀번호

댓글 작성자
 



2016-04-29 01시23분
제가 일하는 환경에서는 아직도 닷넷 프레임워크 2.0(과 4.0 병행이지만 소스를 동일하게 유지하다 보니 2.0기반만 사용)으로 작동중이라 슬픕니다. 좋은 글 감사합니다.
Beren Ko
2020-01-17 10시25분
Oracle.ManagedDataAccess 성능 카운터 활성화

Collect Oracle ODP.NET Perfmon Counters
; https://dotnetdevlife.wordpress.com/2018/03/07/collect-oracle-perfmon-counters/

OraProvCfg /action:register /product:odpm /component:perfcounter /providerpath:"D:\AzureWebTest\oracle.manageddataaccess.dll"

하지만, .NET Core 버전의 Oracle.ManagedDataAccess.Core는 (2020-01-17 기준) 아직 성능 카운터를 지원하지 않음. (https://twitter.com/OracleDOTNET/status/1015717378959822850)
정성태

... 61  62  63  64  65  66  67  68  [69]  70  71  72  73  74  75  ...
NoWriterDateCnt.TitleFile(s)
12211정성태4/27/202019299개발 환경 구성: 486. WSL에서 Makefile로 공개된 리눅스 환경의 C/C++ 소스 코드 빌드
12210정성태4/20/202020772.NET Framework: 903. .NET Framework의 Strong-named 어셈블리 바인딩 (1) - app.config을 이용한 바인딩 리디렉션 [1]파일 다운로드1
12209정성태4/13/202017453오류 유형: 614. 리눅스 환경에서 C/C++ 프로그램이 Segmentation fault 에러가 발생한 경우 (2)
12208정성태4/12/202016027Linux: 29. 리눅스 환경에서 C/C++ 프로그램이 Segmentation fault 에러가 발생한 경우
12207정성태4/2/202015908스크립트: 19. Windows PowerShell의 NonInteractive 모드
12206정성태4/2/202018515오류 유형: 613. 파일 잠금이 바로 안 풀린다면? - The process cannot access the file '...' because it is being used by another process.
12205정성태4/2/202015129스크립트: 18. Powershell에서는 cmd.exe의 명령어를 지원하진 않습니다.
12204정성태4/1/202015157스크립트: 17. Powershell 명령어에 ';' (semi-colon) 문자가 포함된 경우
12203정성태3/18/202018014오류 유형: 612. warning: 'C:\ProgramData/Git/config' has a dubious owner: '...'.
12202정성태3/18/202021237개발 환경 구성: 486. .NET Framework 프로젝트를 위한 GitLab CI/CD Runner 구성
12201정성태3/18/202018484오류 유형: 611. git-credential-manager.exe: Using credentials for username "Personal Access Token". [1]
12200정성태3/18/202018569VS.NET IDE: 145. NuGet + Github 라이브러리 디버깅 관련 옵션 3가지 - "Enable Just My Code" / "Enable Source Link support" / "Suppress JIT optimization on module load (Managed only)"
12199정성태3/17/202016216오류 유형: 610. C# - CodeDomProvider 사용 시 Unhandled Exception: System.IO.DirectoryNotFoundException: Could not find a part of the path '...\f2_6uod0.tmp'.
12198정성태3/17/202019582오류 유형: 609. SQL 서버 접속 시 "Cannot open user default database. Login failed."
12197정성태3/17/202018921VS.NET IDE: 144. .NET Core 콘솔 응용 프로그램을 배포(publish) 시 docker image 자동 생성 - 두 번째 이야기 [1]
12196정성태3/17/202016021오류 유형: 608. The ServicedComponent being invoked is not correctly configured (Use regsvcs to re-register).
12195정성태3/16/202018327.NET Framework: 902. C# - 프로세스의 모든 핸들을 열람 - 세 번째 이야기
12194정성태3/16/202021035오류 유형: 607. PostgreSQL - Npgsql.NpgsqlException: sorry, too many clients already
12193정성태3/16/202018007개발 환경 구성: 485. docker - SAP Adaptive Server Enterprise 컨테이너 실행 [1]
12192정성태3/14/202020042개발 환경 구성: 484. docker - Sybase Anywhere 16 컨테이너 실행
12191정성태3/14/202021100개발 환경 구성: 483. docker - OracleXE 컨테이너 실행 [1]
12190정성태3/14/202015710오류 유형: 606. Docker Desktop 업그레이드 시 "The process cannot access the file 'C:\Program Files\Docker\Docker\resources\dockerd.exe' because it is being used by another process."
12189정성태3/13/202021310개발 환경 구성: 482. Facebook OAuth 처리 시 상태 정보 전달 방법과 "유효한 OAuth 리디렉션 URI" 설정 규칙
12188정성태3/13/202026076Windows: 169. 부팅 시점에 실행되는 chkdsk 결과를 확인하는 방법
12187정성태3/12/202015682오류 유형: 605. NtpClient was unable to set a manual peer to use as a time source because of duplicate error on '...'.
12186정성태3/12/202017451오류 유형: 604. The SysVol Permissions for one or more GPOs on this domain controller and not in sync with the permissions for the GPOs on the Baseline domain controller.
... 61  62  63  64  65  66  67  68  [69]  70  71  72  73  74  75  ...