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)
정성태

1  2  3  4  5  [6]  7  8  9  10  11  12  13  14  15  ...
NoWriterDateCnt.TitleFile(s)
13480정성태12/12/20232636개발 환경 구성: 692. Windows WSL 2 + Chrome 웹 브라우저 설치
13479정성태12/11/20232323개발 환경 구성: 691. WSL 2 (Ubuntu) + nginx 환경 설정
13477정성태12/8/20232511닷넷: 2182. C# - .NET 7부터 추가된 Int128, UInt128 [1]파일 다운로드1
13476정성태12/8/20232252닷넷: 2181. C# - .NET 8 JsonStringEnumConverter의 AOT를 위한 개선파일 다운로드1
13475정성태12/7/20232303닷넷: 2180. .NET 8 - 함수 포인터에 대한 Reflection 정보 조회파일 다운로드1
13474정성태12/6/20232165개발 환경 구성: 690. 닷넷 코어/5+ 버전의 ilasm/ildasm 실행 파일 구하는 방법 - 두 번째 이야기
13473정성태12/5/20232367닷넷: 2179. C# - 값 형식(Blittable)을 메모리 복사를 이용해 바이트 배열로 직렬화/역직렬화파일 다운로드1
13472정성태12/4/20232187C/C++: 164. Visual C++ - InterlockedCompareExchange128 사용 방법
13471정성태12/4/20232248Copilot - To enable GitHub Copilot, authorize this extension using GitHub's device flow
13470정성태12/2/20232546닷넷: 2178. C# - .NET 8부터 COM Interop에 대한 자동 소스 코드 생성 도입파일 다운로드1
13469정성태12/1/20232265닷넷: 2177. C# - (Interop DLL 없이) CoClass를 이용한 COM 개체 생성 방법파일 다운로드1
13468정성태12/1/20232214닷넷: 2176. C# - .NET Core/5+부터 달라진 RCW(Runtime Callable Wrapper) 대응 방식파일 다운로드1
13467정성태11/30/20232254오류 유형: 882. C# - Unhandled exception. System.Runtime.InteropServices.COMException (0x800080A5)파일 다운로드1
13466정성태11/29/20232451닷넷: 2175. C# - DllImport 메서드의 AOT 지원을 위한 LibraryImport 옵션
13465정성태11/28/20232186개발 환경 구성: 689. MSBuild - CopyToOutputDirectory가 "dotnet publish" 시에는 적용되지 않는 문제파일 다운로드1
13464정성태11/28/20232322닷넷: 2174. C# - .NET 7부터 UnmanagedCallersOnly 함수 export 기능을 AOT 빌드에 통합파일 다운로드1
13463정성태11/27/20232225오류 유형: 881. Visual Studio - NU1605: Warning As Error: Detected package downgrade
13462정성태11/27/20232278오류 유형: 880. Visual Studio - error CS0246: The type or namespace name '...' could not be found
13461정성태11/26/20232312닷넷: 2173. .NET Core 3/5+ 기반의 COM Server를 registry 등록 없이 사용하는 방법파일 다운로드1
13460정성태11/26/20232269닷넷: 2172. .NET 6+ 기반의 COM Server 내에 Type Library를 내장하는 방법파일 다운로드1
13459정성태11/26/20232251닷넷: 2171. .NET Core 3/5+ 기반의 COM Server를 기존의 regasm처럼 등록하는 방법파일 다운로드1
13458정성태11/26/20232257닷넷: 2170. .NET Core/5+ 기반의 COM Server를 tlb 파일을 생성하는 방법(tlbexp)
13457정성태11/25/20232183VS.NET IDE: 187. Visual Studio - 16.9 버전부터 추가된 "Display inline type hints" 옵션
13456정성태11/25/20232482닷넷: 2169. C# - OpenAI를 사용해 PDF 데이터를 대상으로 OpenAI 챗봇 작성 [1]파일 다운로드1
13455정성태11/25/20232387닷넷: 2168. C# - Azure.AI.OpenAI 패키지로 OpenAI 사용파일 다운로드1
13454정성태11/23/20232735닷넷: 2167. C# - Qdrant Vector DB를 이용한 Embedding 벡터 값 보관/조회 (Azure OpenAI) [1]파일 다운로드1
1  2  3  4  5  [6]  7  8  9  10  11  12  13  14  15  ...