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)
11992정성태7/22/201911572오류 유형: 560. 서비스 관리자 실행 시 "Windows was unable to open service control manager database on [...]. Error 5: Access is denied." 오류 발생
11991정성태7/18/20199120디버깅 기술: 128. windbg - x64 환경에서 닷넷 예외가 발생한 경우 인자를 확인할 수 없었던 사례
11990정성태7/18/201911319오류 유형: 559. Settings / Update & Security 화면 진입 시 프로그램 종료
11989정성태7/18/201910230Windows: 162. Windows Server 2019 빌드 17763부터 Alt + F4 입력시 곧바로 로그아웃하는 현상
11988정성태7/18/201911680개발 환경 구성: 453. 마이크로소프트가 지정한 모든 Root 인증서를 설치하는 방법
11987정성태7/17/201916671오류 유형: 558. 윈도우 - KMODE_EXCEPTION_NOT_HANDLED 블루스크린(BSOD) 문제 [1]
11986정성태7/17/20199473오류 유형: 557. 드라이브 문자를 할당하지 않은 파티션을 탐색기에서 드라이브 문자와 함께 보여주는 문제
11985정성태7/17/20199579개발 환경 구성: 452. msbuild - csproj에 환경 변수 조건 사용 [1]
11984정성태7/9/201917790개발 환경 구성: 451. Microsoft Edge (Chromium)을 대상으로 한 Selenium WebDriver 사용법 [1]
11983정성태7/8/20198847오류 유형: 556. nodemon - 'mocha' is not recognized as an internal or external command, operable program or batch file.
11982정성태7/8/20198879오류 유형: 555. Visual Studio 빌드 오류 - result: unexpected exception occured (-1002 - 0xfffffc16)
11981정성태7/7/201911031Math: 64. C# - 3층 구조의 신경망(분류)파일 다운로드1
11980정성태7/7/201921480개발 환경 구성: 450. Visual Studio Code의 Java 확장을 이용한 간단한 프로젝트 구축파일 다운로드1
11979정성태7/7/201911020개발 환경 구성: 449. TFS에서 gitlab/github등의 git 서버로 마이그레이션하는 방법
11978정성태7/6/201910372Windows: 161. 계정 정보가 동일하지 않은 PC 간의 인증을 수행하는 방법 [1]
11977정성태7/6/201914933오류 유형: 554. git push - error: RPC failed; HTTP 413 curl 22 The requested URL returned error: 413 Request Entity Too Large
11976정성태7/4/20199310오류 유형: 553. (잘못 인증 한 후) 원격 git repo 재인증 시 "remote: HTTP Basic: Access denied" 오류 발생
11975정성태7/4/201917807개발 환경 구성: 448. Visual Studio Code에서 콘솔 응용 프로그램 개발 시 "입력"받는 방법
11974정성태7/4/201913167Linux: 22. "Visual Studio Code + Remote Development"로 윈도우 환경에서 리눅스(CentOS 7) C/C++ 개발
11973정성태7/4/201912382Linux: 21. 리눅스에서 공유 라이브러리가 로드되지 않는다면?
11972정성태7/3/201915218.NET Framework: 847. JAVA와 .NET 간의 AES 암호화 연동 [1]파일 다운로드1
11971정성태7/3/201912397개발 환경 구성: 447. Visual Studio Code에서 OpenCvSharp 개발 환경 구성
11970정성태7/2/201910706오류 유형: 552. 웹 브라우저에서 파일 다운로드 후 "Running security scan"이 끝나지 않는 문제
11969정성태7/2/201911126Math: 63. C# - 3층 구조의 신경망파일 다운로드1
11968정성태7/1/201917440오류 유형: 551. Visual Studio Code에서 Remote-SSH 연결 시 "Opening Remote..." 단계에서 진행되지 않는 문제 [1]
11967정성태7/1/201911666개발 환경 구성: 446. Synology NAS를 Windows 10에서 iSCSI로 연결하는 방법
... 61  62  63  64  65  [66]  67  68  69  70  71  72  73  74  75  ...