Anda di halaman 1dari 8

8/1/2016

Using.NETStoredProceduresinOracle

SignIn/Register Help Country

Products
OracleTechnologyNetwork

ApplicationDevelopment
Framework
ApplicationExpress
BigData
BusinessIntelligence
CloudComputing
Communications
DatabasePerformance&
Availability
DataWarehousing
Database
.NET
DynamicScriptingLanguages
Embedded

Articles

Solutions

Communities

Downloads

Iama...

Store

Iwantto...

Support

Search

Training

Partners

About

OTN

.NET

Mastering.NETApplicationDevelopmentwithOracle
Using.NETStoredProceduresinOracle
byMarkA.Williams
Astepbystepguidetodeveloping,deploying,anddebuggingyour.NETStoredProceduresinOracleDatabase10gRelease2
Downloadsforthisarticle
Samplecode
OracleDeveloperToolsforVisualStudio.NET,version10.2orlater
OracleDatabase10g,version10.2orlater
PublishedNovember2005
Ifyouarea.NETdeveloper,oneofthemostexcitingfeaturesofOracleDatabase10gRelease2forWindowsistheabilitytoimplementstored
proceduresusingthe.NETlanguageofyourchoice,viaOracleDatabaseExtensionsforNET.
InthisinstallmentofMastering.NETApplicationDevelopmentwithOracle,youwilllearnastepbystepapproachfortakingadvantageof.NET
storedproceduresinyourapplications.Youwilllearnhow.NETstoredproceduresaresupported,howtoinstallandconfiguretheOracle
Databasetoenablesupportfor.NETstoredprocedures,howtodevelopanddeploy.NETstoredprocedures,and,finally,howtodebug.NET
storedprocedures.

DigitalExperience

SupportingArchitecture

EnterpriseArchitecture

PL/SQLstoredproceduresandfunctionsruninthesameprocessastheOracleDatabaseandarestoredinsideofOracle.A.NETstored
procedure,ontheotherhand,runsinanexternalprocessandthe.NETcodeiscompiledintoa".NETassembly,"whichisadynamiclinklibrary
(DLL)filestoredinthefilesystem(usuallyonthesamemachineasthedatabase).The.NETassemblyisloadedintoandexecutedinsideofa
"CLRhost"externalprocessnamedextproc.exe,whichisspawnedbytheWindowsservicenamed<OracleHomeName>ClrAgnt.Whena.NET
storedprocedurecallismade,Oraclecommunicateswiththisexternalprocess,passingintheargumentsandretrievingtheresults.This
communicationishandledbytheOraclemultithreadedagentarchitecture.Totheenduser,a.NETstoredprocedurecallappearstobeno
differentthananyothertypeofstoredprocedurecall.Infact,a.NETstoredprocedurecanbecalledfromanyenvironmentwhereyoucouldcall
aPL/SQLorJavastoredprocedure.

EnterpriseManagement
Identity&Security
Java
Linux
Mobile
ServiceOrientedArchitecture
Solaris
SQL&PL/SQL
SystemsAllArticles
Virtualization

Installationandconfiguration:
IfyouareusingOracleDatabase10gExpressEdition,.NETstoredproceduresareautomaticallyinstalledandconfigurednoadditional
configurationisrequired.IntheStandardandEnterpriseEditions,however,.NETstoredproceduresarenotinstalledandconfiguredbydefault.
Herearebasicinstructionstogeteverythingworkingforthoseinstalls:
DownloadOracleDatabase10.2orlaterfortheWindowsplatform.(Note:.NETstoredproceduresarenotsupportedonanyotherplatform!)
Runtheinstaller(setup.exe).
ChooseAdvancedInstallationandthenCustom.
Alongwithyourotherinstallationchoices,makesuretotickoffOracleDatabaseExtensionsfor.NET.
Whentheinstallationiscomplete,runtheDatabaseConfigurationAssistant(fromtheStartMenu,Oracle,ConfigurationandMigrationTools).
Intheassistant,choosetoconfiguretheOracleDatabaseExtensionsfor.NETdatabaseoption.
Whencomplete,makesurethe<OracleHome>ClrAgentservicehasstarted.
DownloadtheOracleDeveloperToolsforVisualStudio.NETversion10.2orlaterandinstall.Thisversionisrequiredforyoutobeableto
deployyour.NETstoredprocedures.
DevelopandDeploya.NETStoredProcedure
Youwilldevelopanddeployasimple,yetfullyfunctional,.NETstoredproceduretoretrieveacountrynamebasedonacountrycode.Youwill
usethecountriestableintheHRsampleschemathatispartofOracleDatabase10gRelease2.Thecountriestablehasthefollowingstructure:
SQL>desccountries
NameNull?Type

COUNTRY_IDNOTNULLCHAR(2)
COUNTRY_NAMEVARCHAR2(40)
REGION_IDNUMBER
Tocreatethestoredprocedure,youuseanewprojecttypeinVisualStudio.NET2003,the"OracleProject":

CreateanewOracleProjectcalled"MyStoredProcedure"andyouwillseethattheprojectwizardhasaddedareferencetotheOracleData
Providerfor.NETassemblyandaddedtheODP.NETnamespacestotheclassfile.TheVisualStudio.NET2003developmentenvironment
shouldresemblethefollowing:

http://www.oracle.com/technetwork/articles/dotnet/williamssps089817.html

1/8

8/1/2016

Using.NETStoredProceduresinOracle

YouwillreplacetheStoredProcedure1proceduregeneratedbytheprojectwizardwithyourcodetogetacountrynamefromthecountriestable.
YournewprocedurewillacceptacountryIDasanintegerparameterandreturnthecountrynameasastringvalue.Akeypointtonoticeasyou
developyourprocedureisthatthecodeina.NETstoredprocedureisvirtuallyidenticaltothecodeyouuseinastandaloneprogram.Infact,
theonlydifferenceyouwillseeistheconnectionstringusedtoestablishtheconnectiontothedatabase.Hereisthecompletecode:
usingSystem;
usingSystem.Data;
usingOracle.DataAccess.Client;
usingOracle.DataAccess.Types;
namespaceMyStoredProcedure
{
///<summary>
///SummarydescriptionforClass1.
///</summary>
publicclassClass1
{
publicstaticstringGetCountryName(stringCountryID)
{
//usedtoreturnthecountryname
stringCountryName="";
//Getaconnectiontothedb
//contextconnectionisusedinastoredprocedure
OracleConnectioncon=newOracleConnection();
con.ConnectionString="contextconnection=true";
con.Open();
//Createcommandandparameterobjects
OracleCommandcmd=con.CreateCommand();
cmd.CommandText="selectcountry_namefromcountrieswherecountry_id=:1";
cmd.Parameters.Add(":1",OracleDbType.Varchar2,CountryID,ParameterDirection.Input);

//getadatareader
OracleDataReaderrdr=cmd.ExecuteReader();
//getthecountrynamefromthedatareader
if(rdr.Read())
{
CountryName=rdr.GetString(0);
}

//cleanupobjects
rdr.Close();
cmd.Dispose();
//Returnthecountryname
returnCountryName;
}
}
}
Again,otherthanthespecialconnectionstring,thiscodeisidenticaltothatyouwouldincludeinaclientapplication.Thecontext
connection=trueishowyouindicatethatthecodeusestheconnectionoftheprocessthatcalleditandyoumayonlyspecifycontext
connection=truewithinastoredprocedure.TheOracleConnectionhasanewpropertycalledIsAvailablethatyoucanusetodetermine
ifyourcodeisexecutinginthecontextofastoredprocedure.IftheIsAvailablepropertyreturnstrue,thecodeisexecutinginthecontextofa
storedprocedure.Thispropertyreturnsfalseotherwise.Youcaneasilyusethispropertytobuildaconnectionstringbasedonwhetheryour
codeisexecutinginastoredprocedureorinastandaloneapplication.Thisallowsforyoucodetobereusedwithverylittleeffort.
Beforeyoudeployyourstoredprocedure,youmustfirstbuildtheproject.Sinceyouwilldebugyourprocedureafterdeployingit,makesureyou
performadebugbuildoftheproject.Afterbuildingtheproject,youdeployittothedatabaseusingadeploymentwizard.Atthistime,youmust
useaSYSDBAconnectiontothedatabaseinordertodeploythestoredprocedure.IfyoudonothaveaSYSDBAconnectionavailableinthe
DataConnectionnodewithintheOracleDeveloperToolsforVisualStudio.NET,thewizardwillallowyoutocreateone.
Todeploythestoredprocedure,selectBuildDeploySolutionfromtheVisualStudio.NET2003menubar.Thiswillstartthedeployment
wizard:

http://www.oracle.com/technetwork/articles/dotnet/williamssps089817.html

2/8

8/1/2016

Using.NETStoredProceduresinOracle

Afterreviewingtheinformationonthefirststepofthewizard,clickonNext.Youwillthenbepromptedtoselectthedatabaseconnectiontouse.
Ifyoudonothaveadatabaseconnectionalreadydefined,clickontheNewConnectionbutton.Otherwise,choosetheSYSDBAenabled
connectionyouwouldliketouse:

Afterselectingthedatabaseconnectiontouse,clickontheNextbutton.Thisstepinthewizardallowsyoutoselectthedeploymentoptionyou
wishtouse.Becauseyouhavenotyetdeployedthisprocedure,acceptthedefaultoptiontodeploytheassemblyandcreatestoredprocedure
wrappersinthedatabase:

ClickontheNextbuttontoproceed.YouspecifythenameoftheDLLthatwillbeusedwhentheprojecthasbeendeployed:

http://www.oracle.com/technetwork/articles/dotnet/williamssps089817.html

3/8

8/1/2016

Using.NETStoredProceduresinOracle

AcceptthedefaultvaluessuppliedbythewizardandclickonNexttospecifythedirectorytowhichtheprojectwillbedeployed:

SimplyclickonNexttoacceptthedefaultvalues.Thiswilldeploytheprojecttothe%ORACLE_HOME%\bin\clrdirectory.Thenextstepallows
youtospecifywhichmethodstodeploy,theschemainwhichthemethodsshouldbedeployed,thenameofthemethodinthedatabase,the
securitylevel,andthetypemappings:

Todeploytheprojectcorrectly,selecttheGetCountryNamemethod,selectHRastheschema,acceptthesupplieddatabasemethodname,and
acceptthesuppliedsecuritylevel.
Therearethreesecuritylevelsavailable:
Safe:Accesstodatabaseresourcesonly.Noaccesstoresourcessuchasthelocalfilesystemornetworkconnections
External:Accesstoresourcessuchasfilesystemsandnetworkconnections
Unsafe:Norestrictions
Tospecifytheinputandoutputparametermappingsbetweenthedatabaseand.NETdatatypes,clickontheParameterTypeMappingbutton:

http://www.oracle.com/technetwork/articles/dotnet/williamssps089817.html

4/8

8/1/2016

Using.NETStoredProceduresinOracle

Thewizardhasselectedvaluesbasedonthe.NETtypesinyourcode.Acceptthesevaluesastheyareappropriate.
Thefinalstepinthedeploymentwizardpresentsasummaryoftheoptionsselectedandallowsyoutoviewascriptoftheactionstobe
performed.Toperformtheactualdeployment,clickontheFinishbutton.Oncethedeploymentiscompleteyoucanverifythefilehasbeen
createdbyexaminingthedeploymentdirectory:
C:\>dirc:\oracle\10.2\database\bin\clr
VolumeindriveCisLocalDisk
VolumeSerialNumberis94FF538C
Directoryofc:\oracle\10.2\database\bin\clr
09/10/200507:18PM<DIR>.
09/10/200507:18PM<DIR>..
09/10/200507:18PM16,384MyStoredProcedure.dll
1File(s)16,384bytes
2Dir(s)26,689,114,112bytesfree
Toverifythattheprocedurehasbeencorrectlydeployedandfunctionscorrectly,youuseSQL*Plus:
SQL*Plus:Release10.2.0.1.0ProductiononSatSep1019:21:472005
Copyright(c)1982,2005,Oracle.Allrightsreserved.
SQL>connecthr
Enterpassword:
Connected.
SQL>selectGetCountryName('FR')fromdual;
GETCOUNTRYNAME('FR')

France
1rowselected.
YoucanalsoexecutetheprocedureusingtheOracleDeveloperToolsforVisualStudio.NET.Todothis,expandtheHRconnection,expandthe
Functionsnode,selecttheGETCOUNTRYNAMEfunction,rightclick,andselectRun:

ThiswillproducetheRunFunctiondialog:

http://www.oracle.com/technetwork/articles/dotnet/williamssps089817.html

5/8

8/1/2016

Using.NETStoredProceduresinOracle

EnterFRandclickontheOKbutton.ThiswillproducethefollowingresultwindowintheVisualStudio.NET2003IDE:

Debugginga.NETStoredProcedure
InordertodebugthedeployedstoredprocedurefromwithintheVisualStudio.NET2003IDE,youneedtocopytheProgramDebugDatabase
filetothedirectorywheretheDLLwasdeployed.CopytheMyStoredProcedure.pdbfiletothe%ORACLE_HOME%\bin\clrdirectory:
C:\>dirc:\oracle\10.2\database\bin\clr
VolumeindriveCisLocalDisk
VolumeSerialNumberis94FF538C
Directoryofc:\oracle\10.2\database\bin\clr
09/10/200507:32PM<DIR>.
09/10/200507:32PM<DIR>..
09/10/200507:18PM16,384MyStoredProcedure.dll
09/10/200506:44PM11,776MyStoredProcedure.pdb
2File(s)28,160bytes
2Dir(s)26,681,720,832bytesfree
ThedirectorynowcontainsboththeDLLandthe.pdbfile.
BecausetheDLLfileisloadedbytheextproc.exeprocess,youmustattachtothatprocessinVisualStudio.NET2003inordertodebugit.
Sinceyouexecutedthestoredprocedureinthepreviousstep,theextproc.exeprocessshouldberunning.However,ifyouhavenotexecuted
theprocedure,theprocesswillnotberunning.Forthisreason,youshouldexecutetheprocedureeitherthroughSQL*PlusortheOracle
DeveloperToolsforVisualStudio.NETpriortoattemptingtodebugthecode.
Todebugtheprocedure,setabreakpointinthesourcecodeasillustratedhere:

http://www.oracle.com/technetwork/articles/dotnet/williamssps089817.html

6/8

8/1/2016

Using.NETStoredProceduresinOracle

Next,selectToolsDebugProcessesfromtheVisualStudio.NET2003menubar.ThiswillproducetheProcessdialog.Scrolldownthelistof
AvailableProcessesandselectextproc.exe:

ClickontheAttachbuttontoattachtotheextproc.exeprocess.ThisproducestheAttachtoProcessdialog:

Becausetheprocedureyoudevelopedisa.NETprocedure,ensurethattheCommonLanguageRuntimecheckboxisselectedanddeselect
anyothercheckboxes.ClickontheOKbuttontoclosethe"AttachtoProcess"dialogandreturntothe"Processes"dialog.ClickontheClose
buttoninthe"Process"dialogtobeginthedebuggingprocess.
Inordertoinitiatetheprocessandfirethebreakpointyoumustinvoketheprocedure.IntheOracleQueryWindowinVisualStudioorfrom
SQL*Plussessioncalltheprocedureasfollows:

http://www.oracle.com/technetwork/articles/dotnet/williamssps089817.html

7/8

8/1/2016

Using.NETStoredProceduresinOracle
SQL>selectGetCountryName('FR')fromdual;
Note:DonotusetheOracleExplorer"Run"menuitemtofireoffthe.NETprocedureifthebreakpointforthatprocedureissetinsidethatsame
instanceofVisualStudio.ThiswillhangVisualStudioduetodeadlock.
ThiscallwillinvoketheprocedureandSQL*Pluswillappeartohang.However,theprocedureshouldbestoppedatthebreakpointinVisual
Studio.NET2003:

Younowdebugtheprocedureasyouwouldnormallywithstandalonecode.
Thereisanimportantdifferencebetweendebuggingwithanattachedprocessversusdebuggingwithstandalonecode.Becausethe
extproc.exeprocessisexternaltothedevelopmentenvironment,theprocesscanterminateorbekilledwithoutthedebuggingenvironment
detectingthissituation.Inthiscase,youwillseeanerrorsuchasthis:
SQL>selectGetCountryName('FR')fromdual
*
ERRORatline1:
ORA28576:lostRPCconnectiontoexternalprocedureagent
ORA06512:atSYS.DBMS_CLR,line234
ORA06512:atHR.GETCOUNTRYNAME,line7
Ifyouencounterthiserror,reexecutingthecalltothestoredproceduretypicallyrestartstheextproc.exeprocess.Othertroubleshootingtips
includeclosingandreconnectingtheconnectionofthecalleraswellaskillingtheextproc.exeandrestartingtheCLRservice(toforce
extproc.exetogetrespawned).
Conclusion
Inthisintroductorylookat.NETstoredproceduresupportinOracleDatabase10gRelease2forWindows,youhavelearnedhow.NETstored
proceduresaresupported,howtoconfiguretheOraclenetworkingcomponents,howtodevelopanddeploya.NETstoredprocedure,andhow
todebugadeployedprocedure.Younowshouldbereadytobegintodevelopanddeploy.NETstoredproceduresinyourenvironment.

MarkA.Williams[mawilliams@cheshamdbs.com]istheauthoroftheODP.NETcolumninOracleMagazine,anOracleACE,anOracleCertified
ProfessionalDBA,andtheauthorofPro.NETOracleProgramming(Apress,2004).WilliamsfocusesonsolutionsforOracleonWindowsand
contributestotheOracleDataProviderfor.NETforumsontheOracleTechnologyNetwork.
Sendusyourcomments

Emailthispage

PrinterView

ORACLECLOUD
LearnAboutOracleCloud
Computing
GetaFreeTrial
LearnAboutDaaS
LearnAboutSaaS
LearnAboutPaaS
LearnAboutIaaS
LearnAboutPrivateCloud
LearnAboutManagedCloud

JAVA
LearnAboutJava
DownloadJavaforConsumers
DownloadJavaforDevelopers
JavaResourcesforDevelopers
JavaCloudService
JavaMagazine

CUSTOMERSANDEVENTS
ExploreandReadCustomer
Stories
AllOracleEvents
OracleOpenWorld
JavaOne
EMAILSUBSCRIPTIONS
SubscribetoOracle
Communications
SubscriptionCenter

COMMUNITIES
Blogs
DiscussionForums
Wikis
OracleACEs
UserGroups
SocialMediaChannels

SERVICESANDSTORE
LogIntoMyOracleSupport
TrainingandCertification
BecomeaPartner
FindaPartnerSolution
PurchasefromtheOracleStore
CONTACTANDCHAT
USSales:+1.800.633.0738
GlobalContacts
OracleSupport
PartnerSupport

Oracle Subscribe Careers ContactUs SiteMaps LegalNotices TermsofUse Privacy CookiePreferences AdChoices OracleMobile

http://www.oracle.com/technetwork/articles/dotnet/williamssps089817.html

8/8

Anda mungkin juga menyukai