IBM
Informix
IBM
Informix
Object
Interface
for
C++
Programmer’s
Guide
Version3.50
SC23-9422-00
IBM
Informix
IBM
Informix
Object
Interface
for
C++
Programmer’s
Guide
Version3.50
SC23-9422-00
Note:
Beforeusingthisinformationandtheproductitsupports,readtheinformationin“Notices”onpageE-1.
ThisdocumentcontainsproprietaryinformationofIBM.Itisprovidedunderalicenseagreementandisprotected bycopyrightlaw.Theinformationcontainedinthispublicationdoesnotincludeanyproductwarranties,andany statementsprovidedinthispublicationshouldnotbeinterpretedassuch.
WhenyousendinformationtoIBM,yougrantIBManonexclusiverighttouseordistributetheinformationinany wayitbelievesappropriatewithoutincurringanyobligationtoyou.
©CopyrightInternationalBusinessMachinesCorporation1996,2008.Allrightsreserved.
Contents
Introduction
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
. vii
AboutThisPublication . . . vii
TypesofUsers . . . vii
SoftwareDependencies . . . viii
NamingConventions. . . viii
DocumentationConventions . . . viii
TypographicalConventions. . . viii
Feature,Product,andPlatformMarkup . . . viii
ExampleCodeConventions . . . ix
AdditionalDocumentation . . . ix
CompliancewithIndustryStandards . . . ix
HowtoProvideDocumentationFeedback . . . x
Chapter
1.
Architecture
of
the
Object
Interface
for
C++
.
.
.
.
.
.
.
.
.
.
.
.
.
.
. 1-1
OperationClasses . . . 1-1
ValueInterfacesandValueObjects . . . 1-3
ClassHierarchy. . . 1-4 ImplementationNotes . . . 1-5
Restrictions . . . 1-5
PassingObjects—CompilerDependency . . . 1-6
InformixDatabaseServerCompatibility . . . 1-6
Internationalization . . . 1-6
ITFactoryListandtheTypeMap . . . 1-7
Chapter
2.
Issuing
Database
Queries
and
Retrieving
Results
.
.
.
.
.
.
.
.
.
.
.
. 2-1
UsingOperationClasses. . . 2-1 CreatingConnections . . . 2-2
FindingSystemNamesandDatabaseNames . . . 2-3
UsingITSystemNameList . . . 2-3
UsingITDBNameList . . . 2-3
ManagingErrors . . . 2-3
ConnectionTransactionStates . . . 2-5
IssuingQueries. . . 2-6 WhentoUsetheDifferentITQueryMethods . . . 2-6
QueryMethodExample . . . 2-7
UsingPreparedStatements . . . 2-8
UsingCursors . . . 2-9
UsingtheLargeObjectManager. . . 2-12 UsingITRoutineManager . . . 2-13
Chapter
3.
Accessing
Data
Values
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
. 3-1
AccessingDataValues . . . 3-1
ValueObjectManagement . . . 3-2
TheITValueInterface . . . 3-3
TheITConversionsInterface . . . 3-4
TheITDatumInterface . . . 3-4
TheITDateTimeInterface . . . 3-4
TheITLargeObjectInterface. . . 3-5 TheITErrorInfoInterface . . . 3-5
TheITRowInterface . . . 3-6
TheITSetInterface. . . 3-6 TheITContainerInterface . . . 3-7
TheITContainCvtInterface . . . 3-8
Chapter
4.
Creating
and
Extending
Value
Objects
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
. 4-1
TheRawDataObject . . . 4-1
BuildingSimpleValueObjects . . . 4-2
ExposingMultipleInterfaces . . . 4-5
ValueObjectsandConnectionEvents . . . 4-9
CreatingRowTypeValueObjects . . . 4-10
CreatingRowTypeValueObjectsWithoutAnOpenConnection . . . 4-10
CreatingCollectionTypeValueObjectsWithoutAnOpenConnection . . . 4-11
ObjectContainmentandDelegation . . . 4-12
DynamicLoading. . . 4-15 MappingFiles . . . 4-15
Guidelines . . . 4-16
Chapter
5.
Operation
Class
Reference
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
. 5-1
ITConnection . . . 5-1 ITConnectionStamp . . . 5-3 ITContainerIter . . . 5-3 ITCursor . . . 5-5 ITCursorUsage. . . 5-6 ITDBInfo . . . 5-7 ITDBNameList . . . 5-8 ITErrorManager. . . 5-8 ITFactoryList . . . 5-9
SuccessfulInitializationVerification. . . 5-10 ITInt8. . . 5-11 ITLargeObjectManager . . . 5-12
AccessingSmartLargeObjectsinNondefaultSBSpaces . . . 5-13
ITMVDesc . . . 5-16 ITObject . . . 5-17 ITPosition . . . 5-17 ITPreserveData . . . 5-17 ITQuery . . . 5-18 ITRoutineManager . . . 5-19 ITStatement. . . 5-20 ITStatementUsage . . . 5-21 ITString . . . 5-22 ITSystemNameList . . . 5-23 ITTypeInfo . . . 5-24
Chapter
6.
Value
Interface
Reference
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
. 6-1
ITContainCvt . . . 6-1 ITContainer . . . 6-2 ITConversions . . . 6-2 ITDateTime . . . 6-2 ITDatum . . . 6-3 ITErrorInfo . . . 6-4 ITEssential . . . 6-4 ITLargeObject . . . 6-5 ITRow . . . 6-6 ITSet . . . 6-7 ITValue . . . 6-7
UseOfITValue::PrintableWithNullValueObjects . . . 6-8
Appendix
A.
Supported
Data
Types
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
. A-1
Appendix
B.
Example
Programs
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
. B-1
Appendix
C.
ITLocale
Class
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
. C-1
AccessibilityfeaturesforIBMInformixDynamicServer . . . D-1
AccessibilityFeatures . . . D-1
KeyboardNavigation . . . D-1
RelatedAccessibilityInformation. . . D-1 IBMandAccessibility . . . D-1
Notices
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
. E-1
Trademarks . . . E-3
Index
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
. X-1
Introduction
AboutThisPublication . . . vii
TypesofUsers . . . vii
SoftwareDependencies . . . viii
NamingConventions. . . viii
DocumentationConventions . . . viii
TypographicalConventions. . . viii
Feature,Product,andPlatformMarkup . . . viii
ExampleCodeConventions . . . ix
AdditionalDocumentation . . . ix
CompliancewithIndustryStandards . . . ix
HowtoProvideDocumentationFeedback . . . x
In
This
Introduction
ThischapterintroducestheIBMInformixObjectInterfaceforC++Programmer’s
Guide. Readthischapterforanoverviewoftheinformationprovidedinthis
publication andforanunderstandingoftheconventionsusedthroughoutthis publication.
About
This
Publication
TheIBM InformixObjectInterfaceforC++Programmer’sGuidedescribeshowto
develop IBMInformixclientapplicationsusingtheobject-orientedC++
programming language.TheIBM InformixObjectInterfaceforC++encapsulates IBM InformixDynamicServer featuresintoan easy-to-useclass hierarchyand extensible objectlibrary.
TheObject InterfaceforC++isdocumentedinthis publication.TheDataBladeAPI isdocumentedintheIBMInformix DataBladeAPIProgrammer’sGuide.TheGLS API, fromwhichtheObjectInterfaceforC++ITLocaleclass isderived,is documented intheIBM InformixGLSUser’sGuide.Youcanobtaintheseonline publicationsattheIBM® Informix®InformationCenterathttp://
publib.boulder.ibm.com/infocenter/idshelp/v115/index.jsp.
Thispublicationrefersextensivelytotheexampleprogramsincludedwiththe Object InterfaceforC++.For alistoftheexamplesand thefunctionsthey illustrate,seeAppendixB.
Types
of
Users
Thispublicationiswrittenfortwoaudiences:
v DevelopersusingC++tocreatedatabase clientapplicationsforInformixservers
v
DataBladedeveloperswho useObjectInterfaceforC++tocreatevalue objects
thatallowC++clientapplicationstosupportDataBlademoduledatatypes Tousethispublication,youshouldknowC++. FamiliaritywiththeMicrosoft®
ComponentObjectModel(COM)isalso helpfulwhenworking withtheObject InterfaceforC++.
Software
Dependencies
TousetheObjectInterfaceforC++,youmustbe runningIBM InformixDynamic Server Version7.x,9.x,10.x,or11.x.
Naming
Conventions
All publicnamesintheObjectInterfaceforC++beginwithIT.
Documentation
Conventions
Thissectiondescribes thefollowingconventions,whichare usedintheproduct documentationforIBMInformixDynamic Server:
v Typographicalconventions
v Feature,product,and platformconventions
v Examplecodeconventions
Typographical
Conventions
Thispublicationusesthefollowingconventionstointroducenewterms,illustrate screendisplays,describecommandsyntax,andsoforth.
Convention Meaning
KEYWORD KeywordsofSQL,SPL,andsomeotherprogramminglanguagesappear inuppercaselettersinaseriffont.
italics Withintext,newtermsandemphasizedwordsappearinitalics.Within syntaxandcodeexamples,variablevaluesthatyouaretospecify appearinitalics.
boldface Namesofprogramentities(suchasclasses,events,andtables), environmentvariables,filenames,pathnames,andinterfaceelements (suchasicons,menuitems,andbuttons)appearinboldface.
monospace Informationthattheproductdisplaysandinformationthatyouenter appearinamonospacetypeface.
KEYSTROKE Keysthatyouaretopressappearinuppercaselettersinasansserif font.
> Thissymbolindicatesamenuitem.Forexample,“ChooseTools> Options”meanschoosetheOptionsitemfromtheToolsmenu.
Feature,
Product,
and
Platform
Markup
Feature, product,andplatformmarkupidentifies paragraphsthatcontain
feature-specific,product-specific,orplatform-specificinformation.Someexamples of thismarkupfollow:
Dynamic Server
Identifies informationthatisspecific toIBMInformixDynamicServer
End ofDynamicServer WindowsOnly
Identifies informationthatisspecific totheWindows operatingsystem
Thismarkupcanapplytooneormoreparagraphswithina section.Whenan entiresection appliestoa particularproductorplatform,thisisnotedaspartof theheadingtext,forexample:
TableSorting(Windows)
Example
Code
Conventions
Examples ofSQLcodeoccur throughoutthispublication.Exceptasnoted,thecode isnotspecifictoanysingleIBMInformix applicationdevelopmenttool.
IfonlySQLstatementsare listedintheexample,theyare notdelimitedby semicolons. Forinstance,youmightseethecode inthefollowingexample:
CONNECT TO stores_demo ...
DELETE FROM customer
WHERE customer_num = 121
...
COMMIT WORK DISCONNECT CURRENT
TousethisSQLcodefor aspecificproduct, youmust applythesyntaxrulesfor thatproduct. Forexample,ifyouareusingDB–Access,youmustdelimit multiple statementswith semicolons.IfyouareusinganSQLAPI, youmust useEXECSQL at thestartofeachstatementanda semicolon(orotherappropriatedelimiter)at theendofthestatement.
Tip: Ellipsispoints inacodeexampleindicatethatmorecodewouldbe addedin
afullapplication,butit isnotnecessarytoshowittodescribetheconcept beingdiscussed.
For detaileddirectionsonusingSQLstatementsforaparticularapplication development toolorSQLAPI, seethedocumentationforyourproduct.
Additional
Documentation
Youcanview,search,andprintalloftheproductdocumentationfromtheIBM Informix DynamicServerinformationcenter ontheWebat http://
publib.boulder.ibm.com/infocenter/idshelp/v115/index.jsp.
For additionaldocumentationaboutIBM InformixDynamicServerand related products,includingreleasenotes,machinenotes,and documentationnotes,go to theonline productlibrarypageathttp://www.ibm.com/software/data/informix/ pubs/library/.Alternatively,youcanaccessorinstalltheproductdocumentation fromtheQuickStartCDthatisshippedwiththeproduct.
Compliance
with
Industry
Standards
TheAmericanNationalStandardsInstitute(ANSI)andtheInternational Organization ofStandardization(ISO)havejointlyestablished asetof industry standards fortheStructuredQuery Language(SQL). IBMInformixSQL-based productsare fullycompliantwith SQL-92EntryLevel (publishedasANSI X3.135-1992), whichisidenticaltoISO9075:1992.Inaddition,manyfeaturesof IBM Informixdatabaseserverscomplywith theSQL-92IntermediateandFull Level andX/OpenSQLCommonApplicationsEnvironment (CAE)standards.
How
to
Provide
Documentation
Feedback
Youare encouragedtosend yourcommentsaboutIBM Informixuser documentationbyusingoneof thefollowingmethods:
v GototheInformationCenterathttp://publib.boulder.ibm.com/infocenter/
idshelp/v115/index.jspandopenthetopicthatyouwanttocommenton.Click
Feedbackat thebottomofthepage,fillouttheform,andsubmityourfeedback. Feedbackfrombothmethodsismonitored bythose whomaintaintheuser
documentationofDynamicServer. Thefeedbackmethodsare reservedfor reporting errorsandomissionsinourdocumentation. Forimmediatehelpwith a technicalproblem,contactIBM TechnicalSupport.For instructions,seetheIBM Informix TechnicalSupportWebsiteathttp://www.ibm.com/planetwide/. Weappreciateyoursuggestions.
Chapter
1.
Architecture
of
the
Object
Interface
for
C++
OperationClasses . . . 1-1
ValueInterfacesandValueObjects . . . 1-3
ClassHierarchy. . . 1-4 ImplementationNotes . . . 1-5
Restrictions . . . 1-5
PassingObjects—CompilerDependency . . . 1-6
InformixDatabaseServerCompatibility . . . 1-6
Internationalization . . . 1-6
ITFactoryListandtheTypeMap . . . 1-7
In
This
Chapter
TheIBM InformixObjectInterfaceforC++encapsulatesInformix databaseserver featuresintoa classhierarchy.
OperationclassesprovideaccesstoInformixdatabasesand methodsforissuing
queries andretrievingresults.Operationclassesencapsulatedatabaseobjectssuch asconnections,cursors, andqueries.Operationclass methodsencapsulatetasks suchasopeningand closingconnections,checkingandhandlingerrors,executing queries, definingand scrollingcursors throughresult sets,andreadingand writing largeobjects.
Valueinterfacesareabstractclassesthatprovidespecific applicationinteraction
behaviorsforobjectsthatrepresentIBMInformixDynamic Serverdatabasevalues (value objects).Extensiblevalue objectsletyouinteractwith yourdata.Built-in value objectssupportANSISQLandC++basetypesandcomplextypessuchas rowsandcollections.YoucancreateC++objectsthatsupportcomplexand opaque datatypes.
Operation
Classes
Object InterfaceforC++applicationscreateinstancesofpublicoperationclasses, whichcontainpointerstoaprivate implementationclasses.
Althoughthis interface/implementationapproachaddsanextralevelof indirection,it providesimportantbenefits:
v Applicationsdonotdependontheimplementationoftheunderlyingclass
becausetheimplementationclassisinaccessible.
v Performanceofcopyoperationsisimprovedbecauseapplicationscopyonlythe
implementationpointerof theobjectandnottheentireobject.
v Applicationscaneasilyuseautomaticvariablesasopposedtoheap-allocated
variables.Automaticvariablesareautomaticallydeallocatedwhentheypassout ofscope,whichhelpsavoidmemoryleaks.Theimplementationclasstracks referencestoobjects,destroyingobjectsonlywhentheyarenolongerreferenced. Figure1-1illustratestherelationshipbetweenthepublicinterfaceclassesand private implementationclasses.
The ObjectInterfaceforC++definesthefollowingoperationclasses.
OperationClass Description Page
ITConnection Managesadatabaseconnection. page5-1 ITConnectionStamp Maintainsstampinformationaboutaconnection. page5-3 ITContainerIter ExtractsC++base-typevalues(suchasint,long,ordouble)
fromacontainervalueobject.
page5-3 ITCursor Definescursorsandmanagesresults. page5-5 ITDBInfo Storesdatabaseinformation. page5-7 ITDBNameList Allowstheusertoobtaindatabasenames. page5-8 ITErrorManager Providesbaseclassfunctionalityformanagingerror
callbacks.
page5-8 ITFactoryList AddsmappingsfromIBMInformixDynamicServerdata
typestofunctionsthatbuildvalueobjectstorepresent instancesofthesedatatypes.
page5-9
ITInt8 Providesan8-byteintegerclass. page5-11 ITLargeObjectManager Supportslargeobjects. page5-12 ITLocale ProvidesGLSsupport. Onlinenotes ITMVDesc Notanoperationclass,butadescriptorthatholdsthe
instanceinformationnecessarytocreateavalueobject.
page5-16 ITObject Providesthebaseclassforpublicoperationclassinterface
objects.
page5-17 ITPreserveData Providesaninterfaceformaintainingareferencetodatabase
datareceivedfromtheserver,forusebytheimplementerof avalueobject.
page5-17
OperationClass Description Page
ITQuery IssuesSQLqueriestoanIBMInformixDynamicServer database.
page5-18 ITRoutineManager ProvidesfastpathexecutionofDataBladeAPIfunctions. page5-19 ITStatement Providessupportfortheexecutionofpreparedqueriesthat
returnnorows.
page5-20 ITString Providesastringclass. page5-22 ITSystemNameList Allowstheusertoobtainhostsystemnames. page5-23 ITTypeInfo Storesinformationaboutdatabasetypes. page5-24
For detaileddescriptionsoftheseoperationclasses,refertoChapter5,“Operation Class Reference,”onpage5-1.
Value
Interfaces
and
Value
Objects
TheObject InterfaceforC++creates C++objectsthatencapsulate dataretrieved froma database.Thesevalue objectsarecreatedbytheObjectInterfaceforC++ usinganextensibleclassfactorythatmapsserverdatatypestoC++objects.
DataBlade®developerscancreatevalue objectsthatrepresentnew DynamicServer
datatypes. DeveloperscanusetheObjectInterfaceforC++towriteclient applicationsthatoperatewiththese newvalueobjects.ObjectInterfaceforC++ client applicationsdo notdepend ontherepresentation oftheobjectinthe database;if thedatabase representationchanges,thecorrespondingvalue object canbe alteredandtheexistingapplicationswillcontinuetorun. Codeforvalue objectscanbe compiledintoanapplicationordynamically loadedintoan application fromsharedlibraries.
Thevalue objectdesigniscompatiblewiththeMicrosoftCommonObject Model (COM)inthesensethatit enablesobjectstoexposebehaviorsthroughinterfaces.
An interfaceisanabstractclassthatencapsulatesthemethodsassociatedwitha specific behavior.
For example,toindicatethatan objectcanbehaveasa container,theobject exposestheITContainerinterface;toindicatethatanobjectcanconvertitsvalue toa C++basetype(suchasintordouble),anobjectexposestheITConversions
interface;and soon.
Interfaces areextractedfromanobjectbycalling aQueryInterface()function providedin ITEssential,whichisthebaseclassofall valueinterfaces.Whenthe
QueryInterface()function iscalled,thecallerspecifiestheinterfaceIDofthe desiredinterface.Iftheobjectexposestherequestedinterface,then
QueryInterface()returnsIT_QUERYINTERFACE_SUCCESSandsetsitssecondargument totheaddressof thedesiredinterface.
Figure1-2illustratestherelationshipoftheapplicationinterface tothe implementation.
The ObjectInterfaceforC++definesthefollowingvalueinterfaces.
Interface Description Page
ITContainCvt DecomposesanobjectintoC++basetypeinstances. page6-1 ITContainer Providesaccesstothecontainermembers. page6-2 ITConversions ConvertsdatatoC++baseclassesorstrings. page6-2 ITDateTime Allowsaccesstothefieldsofadatabasedate/timeobject. page6-2 ITDatum Supportsthefunctionalityofthebasicvalueobject,including
accesstotheunderlyingdata.
page6-3 ITErrorInfo Exposeserrorinformationonobjectsforwhichillegal
operationscancauseservererrors.
page6-4 ITEssential Servesasthebaseofthevalueinterfaceclasses. page6-4 ITLargeObject Manipulatesalargeobjectreturnedbyaquery. page6-5 ITRow Providesaccesstorowvalues. page6-6 ITSet Providesaccesstocollectionresults. page6-7 ITValue Supportsthebasicvalueobject’sfunctionality. page6-7
Class
Hierarchy
The followingdiagramshowstheObjectInterfaceforC++inheritancehierarchy.
Implementation
Notes
ThefollowingsectionsdiscussObjectInterfaceforC++programmingrestrictions and practices.
Restrictions
TheObject InterfaceforC++issubjecttothefollowingrestrictions:
v TheObjectInterfaceforC++doesnotsupport objectpersistenceforapplication
classes;itdoesnotautomaticallymapinstancesofdatabasetablestoapplication classesorviceversa.
v
Youcannotdirectlyupdatethedatabasedatabymodifyingthecorresponding
valueobjects;tomodifythedatabasedatathatcorrespondstothedatareturned toclientprogramsinvalueobjects,youmustissueSQLqueries, orthemethods
ITCursor::UpdateCurrent()andITCursor::DeleteCurrent().
v YoucannotdevelopserverfunctionsusingtheObjectInterfaceforC++.
v YoushouldnotmixdatabaseaccessthroughtheObjectInterfaceforC++and
lower-levelinterfaces(liketheDataBladeAPI)inthesameapplication.
Figure1-3.C++InheritanceHierarchy
v InstancesofITConnectioncannotbe sharedacrossthreadboundariesina
multithreadedenvironment.
Passing
Objects—Compiler
Dependency
Whenyoupassanobjectto afunctionbyvalue,theC++compilercreatesa temporary copyoftheobjecttopasstothefunction.Thecompilerdestroysthe objectafter thefunction returns.Theexacttimeatwhichtemporaryobjectsare destroyediscompiler-dependent.For thisreason,your applicationshouldnotrely ontheautomaticdestructionoftemporaryobjects.
For example,ifyoupassanITConnectionobjecttoa functionbyvalueand invoke theAddCallbackmethodontheconnectioninsidethefunction,thetemporary connection object(onwhichyouadded thecallback)mightormight notexist immediatelyafter thefunction returns.Becauseboththeoriginalconnectionobject and thecopyrefertothesameunderlying serverconnection,thenewcallback might ormightnotremainineffectontheunderlyingconnectionwhenyour function returns.
Toensureconsistent behavior,callDelCallbackinsideyour functionwhenthenew callbackisnolongerrequired.Donotrelyontheautomaticdestructionofthe connection objectparameterbythecompilertoremovethecallbackfromthe underlyingserverconnection.For detailsaboutDelCallback,referto
“ITErrorManager” onpage5-8.
Informix
Database
Server
Compatibility
The ObjectInterfaceforC++canbe usedtocreatedatabase clientapplicationsthat runagainstIBMInformixDynamicServer databases.However, classesand
methodsthatsupportversion9,xand 10.xextensibilityfeaturesarenotsupported with version7.xdatabases.
IBM InformixDynamicServer version7.xdoesnotsupport theboolean,int8,
blob,clob,orlvarchardatatypesortheDynamicServer extendeddatatypes: opaque,distinct,row,andcollection.
Some oftheObjectInterfaceforC++examplesworkonlywithDynamicServer version 9.xand10.x,sincetheversion7.xDynamicServer SQLparserdoesnot support DynamicServer datatypecastingsyntax(value::data_type)inSQL statements.
Object InterfaceforC++dynamicloadingandobjectdelegationtechniqueareonly usefulwith DynamicServer databases.
Internationalization
The ObjectInterfaceforC++provides functionalitybasedonIBMInformixGlobal LanguageSupport.Formoreinformation,seetheIBM InformixGLSUser’sGuide.
The ITLocaleclass,describedinAppendixC, encapsulatestheGLSAPI.It provides methodstoperform locale-sensitiveconversionsbetweenthetextand binary formsofthedate,time, numeric,andmoneydatatypes. Italsoprovides support formultibytecharacterstringsandforquotedtypenames.
CallITLocale::Current()toobtainapointertothecurrentclientlocaleand use
TheITString classencapsulatesa stringina clientlocale.Whena stringis retrievedfroma server,it isconverted totheclientlocale.Locale-specific rules governthefollowingoperations:
v Date/time,numeric,andmoneystringformatting
v Errormessages producedbytheObjectInterfaceforC++
v StringoperationssuchasTrim(),concatenation,and soon
Clientlocale isestablished attheapplication’sstartuptimebasedonthevalueof theCLIENT_LOCALE environmentalvariable.
ITFactory
List
and
the
Type
Map
Type namesfortheITFactoryList constructororinthetypemapfilecancontain anycharactersinthecurrentclientlocale,exceptNULL. Typenamescancontain multibyte characters.Ifatype nameincludeswhitespacecharacters,enclosethe type nameina pairofdoublequotesinthetypemapfile.Ifthetypename contains adoublequotecharacter,placeadouble quotecharacterbeforeit. Type namesearchesinthecurrentclientlocalearecaseinsensitive.
Chapter
2.
Issuing
Database
Queries
and
Retrieving
Results
UsingOperationClasses. . . 2-1 CreatingConnections . . . 2-2
FindingSystemNamesandDatabaseNames . . . 2-3
UsingITSystemNameList . . . 2-3
UsingITDBNameList . . . 2-3
ManagingErrors . . . 2-3
ConnectionTransactionStates . . . 2-5
IssuingQueries. . . 2-6 WhentoUsetheDifferentITQueryMethods . . . 2-6
ExecForStatus . . . 2-6
ExecOneRow . . . 2-7
ExecToSet. . . 2-7 ExecForIteration . . . 2-7
QueryMethodExample . . . 2-7
UsingPreparedStatements . . . 2-8
UsingCursors . . . 2-9
UsingtheLargeObjectManager. . . 2-12 UsingITRoutineManager . . . 2-13
In
This
Chapter
Tointeractwith adatabase,your C++client applicationusestheoperationclasses of theIBM InformixObjectInterfaceforC++.Theseclasseshavemethodsfor opening databaseconnections,submitting queries,andmanipulatingdatabase cursors. Thischapterdescribeshow tousethesemethods.
Using
Operation
Classes
Thecsql.cpp exampleisa smallapplicationthatusestheITQueryand
ITConnectionclassestoprovideasimple commandlineinterfacethatacceptsSQL commandsfromthestandardinput,transmitsthecommandstothedatabase,and displays theresults.Themajorstepsoftheprogramareasfollows.
1. Opentheconnection.
Beforeanydatabaseinteractioncantakeplace,theconnectionwith the databasemust beestablished.Openingtheconnectionwithoutanyarguments instructstheinterfacetousethedefaultsystem,database,user name,and password.For detailsaboutconnection defaults,referto“ITDBInfo”onpage 5-7.
ITConnection conn; conn.Open();
2. BuildanITQueryobjectfortheconnection.
ITQuery query(conn);
Aqueryobjectisusedtoissuedatabasequeries andtoaccessresultsets.An operationclassisalwayscreatedinthecontextofa serverconnection. 3. Readlinesofinputfromstdin,usingtheC++iostreamlibrarymethods.
while (cin.getline(qtext, sizeof(qtext))) {
}
4. Executethequeryread fromstdin,usingtheExecForIterationmethodof the
queryobject.
if (!query.ExecForIteration(qtext)) {
}
5. Loop throughtheresultrowsofthequery.
ITRow *comp; int rowcount = 0;
while ((comp = query.NextRow()) != NULL) {
}
Arowisextractedfromtheresultsetof aqueryusingthequeryobject’s
NextRowmethod.Thecodeshowsthedeclarationof apointertotherow interfacefor anobjectthatreceivestheresultdata,andtheloopthatreadsthe result dataintotherow object.
Thisisan exampleoftheuseofa valueobjectintheprogram:theNextRow
methodreturnsa pointertoanITRowinterface.Thepointer returnedby
NextRowisnotapointertoanactualobject; itisapointertoaninterface that isexposedbyanobject.
6. Printtherow.
cout << comp->Printable() << endl;
Everyvalue objectexposinganITValueorITValue-derivedinterface supports thePrintablemethod,whichreturnstheobjectasaprintablestringina constantITStringobject. Thisobjectcanbeputdirectlyonthestdoutstream. For detailsabouttheITStringclass,referto“ITValue”onpage6-7.
7. Releasetherow.
comp->Release();
Thevalue interfacereturnedtotheapplication mustbe explicitlyreleasedby theapplication.Avalue objectkeepstrack ofthenumberofoutstanding referencestoit,andwhenthelastreferenceisreleased,destroysitself. 8. Closetheconnection.
conn.Close();
Closinga connectiondestroysanysaveddataassociatedwiththeconnection. Becausea valueobjectmayholda referencetothissaveddata,itmustkeeptrack of whethertheunderlyingdatahasbeendestroyed.Fordetails, referto“Value Object Management”onpage3-2.
Creating
Connections
Tospecifyconnectionparameters(system,database,username, andpassword) when creatingaconnection,yourapplication createsaninstance oftheITDBInfo
class.Iftheapplication usesthedefaultconnectionparameters, youcancreatea connection withoutusinganinstanceoftheITDBInfo class.
AfteranITDBInfo variableisconstructed,itcanbeusedtoestablishmultiple database connections.However,after aconnectionhasbeenestablishedusinga givenITDBInfo,thatinstance ofITDBInfocannotbechanged,norcananycopy of itbemodified. TheITDBInfoinstanceissaidtobe frozen.Todetectwhetheran
ITDBInfo objecthasbeenfrozen,usetheITDBInfo::Frozen() method.
The defaultusernameandpasswordare thoseofthecurrentuser.Thedefault database nameisthecurrentuser’sname.Thedefaultservernameisspecifiedin theUNIX® $INFORMIXSERVERenvironmentvariable orintheWindows®
registry.IftheITDBInfo instanceisnotfrozen,youcanmodify thesevalueswith theITDBInfo::SetDatabase(),ITDBInfo::SetUser(),ITDBInfo::SetPassword(),and
ITDBInfo::SetSystem() methods.
Finding
System
Names
and
Database
Names
Manyclientapplicationsdeterminewhatdatabasetouseatruntime,sometimes allowing userstoselectfromalternatives.YoucanusetheITSystemNameListclass and theITDatabaseNameList classtoretrievelistsofInformixservers and
databases. Thefollowingsectionsdescribehow tousetheseclasses.
Using
ITSystemNameList
Thefollowingexcerptsfromsysname.cppillustratetheuseofITSystemNameList. 1. TheCreate()methodcreates thesystemnamelistbylookingintothesqlhosts
file(onUNIX)orfromtheregistryentryunderthe
HKEY_LOCAL_MACHINE\Software\Informix\sqlhostskey(onWindows).
ITSystemNameList list;
ITBool created = list.Create();
2. TheITSystemNameList::NextSystemName() methoddisplaysthesystemname
list.
while (ITString::Null != (current = list.NextSystemName()))
{
cout << current << "\tALWAYS_DIFFERENT" << endl; last = current;
}
Using
ITDBNameList
Thefollowingexcerptsfromdbname.cpp illustratetheuseofITDBNameList. 1. ITDBNameList::Create()creates aninstanceofITDBNameListthatliststhe
databasesfromtheservers containedintheDBPATHandINFORMIXSERVER
environmentvariables.
ITDBNameList dbnl; ITBool created;
created = dbnl.Create();
2. TheITDBNameList::NextDBName()methoddisplays thedatabase namelist.
void
DisplayITDBNameList(ITDBNameList &dbname) {
ITString str;
cout << "Parsing the DBNameList by calling NextDBName() method "<< endl;
while (ITString::Null != (str = dbname.NextDBName())) cout << str << "\tALWAYS_DIFFERENT" << endl ;
}
Managing
Errors
Mostoperations,suchasissuing queries,fetchingrows,andsettingtransaction states,return aresultcode thatyourapplicationshouldcheck.Operationsthat return pointerstypicallyreturnNULLtoindicateanerror. Operationsthatreturn a Boolean resulttypicallyreturnFALSEtoindicateanerror.
Tospecifya routinetobecalledwheneveranerrororwarningisposted,your application canassociateacallbackfunctionwith aninstanceofthese classes.Ifan erroroccurs, thecallbackfunctionisexecuted.Seepage5-8forthecallback function signature.
Tocheck errorsfromoperationobjects,calltheErrorandErrorText methodsafter an operationisperformed, orincludecallstotheErrorandErrorTextmethodsin thebodyofanerrorcallbackfunctionaddedtotheobject.Within anerrorcallback function, theonlysafeoperationsarecalls totheError,ErrorText,Warn,
WarningText,and SqlStatemethodstoexaminetheErrorManagerobject. Yourown datastructurescanbeaccessedwith theuserdataparameter,whichis untouched bytheObjectInterfacefor C++.Anyoperationsinthecallbackfunction thatare performedusingtheObjectInterfaceforC++, suchascallstothe
operationclassmethodsthatsubmitqueries,haveundefinedresults.
The ITErrorManagerbaseclassgivesitsderivedclassestheabilitytomanage errors returnedbytheserverorgeneratedwithintheObjectInterfaceforC++. Callbacksaddedtoan operationclass derivedfromITErrorManagerare addedto thatinterface object.Iftheinterfaceobjectisdestroyed,thecallbacksregisteredon thatinterface areremoved.Iftheinterface objectisdestroyedwhilethe
implementationisstillpresentandthecallbackswerenotremoved,thereisno validinterface objectreferencefor thefirst parameterofthecallbackwhenthe implementationcallsthecallback,and asegmentation violationmayoccur.The destructorof ITErrorManagerremovessuchacallback.
Totrack allerrorsonaconnection,set acallbackfunctionontheconnectionobject. Whenprocessingerrorsfromaconnectionobject, besuretocheck thereturnstatus fromtheoperationitself,andnotfromtheErrormethod.Totrackallerrorsfora specific object,set acallbackfunctionontheobjectitself.
The csql2.cppexampleconsistsofthecsql.cppSQLinterpreterexampleenhanced with error-handlingcode.Thefollowingstepsdescribetheerror-handling features usedinthecsql2.cppexample:
1. Addtheerrorcallbackfunction:
ITCallbackResult
my_error_handler(const ITErrorManager &errorobject,
void *userdata, long errorlevel)
{
// Cast the user data into a stream ostream *stream = (ostream *) userdata; (*stream) << "my_error_handler: errorlevel=" << errorlevel << " sqlstate=" << errorobject.SqlState() << ’ ’ << errorobject.ErrorText() << endl; return IT_NOTHANDLED; }
Theargumentstothecallbackfunction aretheobjectonwhichtheerror appeared,afield(userdata) passedtothecallbackfunction, andanindicatorof theseverityoftheerror(fordetailsaboutlevelsoferrors,referto
“ITErrorManager”onpage5-8).Inthisexample,thecallbackfunctioncaststhe user datafieldintoaC++ostreamobjectandprintstheerrortextand SQL
errorcode(theISOstandardSQLSTATE)ontheoutputstream. Theuserdata intheexamplemustbe anostreampointer.
2. Addthecallbackfunction totheerrorhandler listmaintainedbythequery
object:
query.AddCallback(my_error_handler, (void *) &cerr);
Thefollowingdialogshowshow thecsql2.cppprogramhandlesanerroneousSQL statement.Attheprompt(>), theuser typeserror;(whichisnotvalidSQL)and thecsql2.cppprogram’serrorhandlerdisplays anerrormessage:
% csql2
Connection established > error;
my_error_handler: errorlevel=2 sqlstate=42000 X42000:-201:Syntax error or access violation Could not execute query: error;
0 rows received, Command: >
Connection
Transaction
States
Aconnectiontoa databaseissaidtobe inoneofanumber oftransactionstates.
Transactionstatesshowhowqueriessubmitted ontheconnectionare committed. Some serveroperationscanonlytakeplacewithina transaction.Forexample, updateablecursors canonlybe openedwithina transaction.
TheITConnectionclassisusedtomanageconnectionsandincludesmethodsto set andinquireaboutthetransactionstate.Thefollowingtablelists theconnection transactionstates.
State EffectofSettingThisState
SignificanceWhenRetrieved fromITConnection
None Illegaltoset Notconnectedtoaserver Auto Illegaltoset Inautocommitmode(eachSQL
statementisaseparate transaction)
Begin Startatransaction Enteredorinatransaction Commit Committhetransaction Lasttransactionwasjust
committed
Abort Abortthetransaction Lasttransactionwasjust aborted/rolledback
Thecsql3.cppexampleaddstransactionmonitoringcapabilitiestotheSQL interpreterexample.Thefollowingstepspointoutthetransactionmonitoring features:
1. Ifthesessioniswithina transaction,print "TRANSACTION>"astheprompt.The
followingcodeshowstheuseof theGetTransactionStatemethod tocheckthe transactionstate: if (conn.GetTransactionState() == ITConnection::Begin) { cout << "TRANSACTION> "; } else { cout << "> "; }
2. Ifthesessionexits whileitiswithina transaction,abortthetransaction. The
dataisreturnedtothestateitwasin whenthetransactionstarted.The followingcodeshowstheuseof theGetTransactionStatemethod tocheckthe transactionstateand SetTransactionStatetoset thestate:
if (conn.GetTransactionState() == ITConnection::Begin) {
cerr << endl
<< "Exit within transaction, aborting transaction" << endl;
conn.SetTransaction(ITConnection::Abort);
}
The outputfromtheexampleissimilartothefollowing,whentheuser exitsafter issuing a begin workstatement:
% csql3
Connection established > begin work;
0 rows received, Command:begin work TRANSACTION> EOF
Exit within transaction, aborting transaction
Issuing
Queries
Thereare anumberofdifferentwaystoissueSQLqueries intheObject Interface for C++,eachsuitablefordifferentapplicationrequirements. Thefollowingtable summarizesthemethodsusedforissuing queries.
Method Description
ITQuery::ExecForStatus Executeaquerythatdoesnotreturnrows(suchasCREATE,INSERT, UPDATE,orDELETE).Returnaresultcodethatsayswhetherthe queryresultedinaservererror.
ITQuery::ExecOneRow Executeaquerythatreturnsonerow;flushanyresultsotherthanthe firstrow.Usefulforquicklysubmittingqueriesthatonlyreturna singlerow, suchas selectcount(*) fromsystables.
ITQuery::ExecToSet Executeaqueryandretrievealltheresultrowsintoasavedrowset managedontheclient.
ITQuery::ExecForIteration Executeaqueryandreturnonerowtotheapplicationoneverycall toITQuery::NextRow.
ITCursor::Prepare/ ITCursor::Open
Defineacursorforaselectstatementandreturnrowstotheclienton callstoITCursor::Fetch.
ITStatement::Prepare/ ITStatement::Exec()
Prepareandexecuteaquerythatreturnsnorows.
When
to
Use
the
Different
ITQuery
Methods
The followingsectionstellyouhow tousetheObjectInterfaceforC++query methodsappropriately.
ExecForStatus
Use theExecForStatusmethodoftheQueryobjectforquerieswhenthe application doesnotneed anydatareturnedfromthequery(forexample,DDL statements suchasCREATETABLE,DROPTABLE,CREATEVIEW,orDML statements suchasUPDATE).TheExecForStatusmethodreturnsFALSE ifa server erroroccurred.
ExecOneRow
Use theExecOneRow methodoftheQueryobjectforqueriesthatreturn(orare expectedtoreturn) onerow.TheExecOneRow methodreturnsanITRowinterface pointer thatrepresentstheresult row,orNULLif thereisanerrororifnorowis returned. Ifthequeryreturnsmorethanonerow,thefirst rowisreturnedand the restare discarded.
ExecToSet
Use theExecToSetmethod oftheQuery objectforqueries thatreturnmorethan onerow.ExecToSetrunsthequerytocompletionand storestheresultsinthe client program’smemory.Iftheresultsetisverylarge,theclient’smemorymaybe inadequate.TheresultsreturnedbyExecToSetareaccessibleinarbitraryorder. Using ExecToSet,theconnectionischeckedinafterthecalliscomplete.Fordetails aboutcheckingconnectionsinorout,referto“ITConnection” onpage5-1.
ExecForIteration
Use theExecForIteration methodoftheQueryobjectforqueriesthatreturna large result setthatmust beprocessedarowat atime.Afterissuingthequerywith
ExecForIteration,your applicationmust callNextRowtoaccesstheindividual rowsintheresultset.Whileyourapplication isprocessingtherowsreturnedby
ExecForIteration,theconnectiontothedatabaseservercannotbeusedforanother query.Youcan,however,freeuptheconnectiontotheserverbyusingthe
ITQuery::Finishmethodtofinish queryprocessingwithoutretrievingallrows. Thismethodisthequery-executingmechanismmostsimilartoexecutingaselect
statementusingtheDataBladeAPImi_execand mi_next_rowcalls.Also,this method doesnotenablenonsequential accessto therows.
Query
Method
Example
Thequeryex.cppexampledemonstrates useoftheExecForStatus,ExecOneRow, and ExecToSetmethods.Thefollowingexcerptsillustratetheuseofthequery methodsinthequeryex.cppexample:
1. CallITQuery::ExecOneRow()tocheckif thetable informixfansexistsinthe
database.Ifthetabledoesnotexist,useITQuery::ExecForStatus()tocreateit.
// Does the table exist? If not, then create it. ITRow *r1 = q.ExecOneRow(
"select owner from systables where tabname = ’informixfans’;");
if (!r1
&& (!q.ExecForStatus(
"create table informixfans (name varchar(128));"))) {
cerr << "Could not create table ‘informixfans’!" << endl; return 1;
}
2. CallITQuery::ExecToSettofetch theresultsofa selectstatement:
// Show the contents of the table
cout << "These are the members of the Informix fan club, version "; ITValue *rel = q.ExecOneRow
("select owner from systables where tabname = ’ VERSION’;");
cout << rel->Printable() << " ALWAYS_DIFFERENT" << endl; rel->Release();
ITSet *set = q.ExecToSet
("select * from informixfans order by 1;");
if(!set) {
cout << "Query failed!" << endl;
conn.SetTransaction(ITConnection::Abort);
conn.Close(); return -1;
}
ITValue *v;
while ((v = set->Fetch()) != NULL) {
cout << v->Printable() << endl; v->Release();
}
set->Release();
Using
Prepared
Statements
Prepared statementscanbeusedtoperformINSERT,UPDATE,andDELETE functionsefficientlyandtopassbinarydataasparameters. TheObjectInterfacefor C++encapsulatespreparedstatementfunctionalityintheITStatementclass.The followingexcerptsillustratetheuseoftheloadtab.cppexampletoload atable froma textfileusinga preparedstatement.
1. Touseapreparedstatement, theapplicationcreatesaninstance ofITStatement
ontheopenedconnection.
ITStatement stmt(conn);
2. Theapplication preparestheSQLstatement,whichhastheeffectofcreatingthe
statementparameters.
if(!stmt.Prepare(sql))
return -1;
Createdparametershavethevalue NULL.
3. Whentheapplication needstoset aparametervalue, itobtainstheparameter’s ITValue*throughthecalltotheParam() function.
ITValue *param = stmt.Param(paramno);
Theapplication cancalltheNumParams()functiontoobtainthenumberof parameters.
4. Theapplication setstheparametervalue usingITValue::FromPrintable(),orit
obtainstherequiredinterfacebycallingtheQueryInterface()function and usingitsupdateroutines.
if (!param->FromPrintable(pdb))
{
cerr << "Could not set parameter "
<< paramno << " to ’" << pdb << "’" << endl; return -1;
Theapplication needstorelease theparameter’sITValueinterfacebycalling
param->Release().
5. Afterallparametervaluesareset,theapplication executestheprepared query.
if (!stmt.Exec()) {
cerr << "Could not execute statement" << endl; return -1;
The applicationcanusetheRowCount()functiontodeterminethenumberofrows affected bythelastqueryexecuted.Theapplication canthenresettheparameter valuesand re-executethequery.Anyparametervaluesthathavenotbeen reset staythesame.
Aftertheapplicationcompletesworkwiththepreparedstatement, itdropsthe statementusingtheDrop()function.
Thesame instanceofITStatementcanbeusedtoprepareanotherSQLstatement bycallingPrepare(),whichhastheeffectofcallingDrop()foranycurrently prepared statement.
Using
Cursors
Cursors canbeusedtoefficientlyperform SELECTstatementswithparameters and topassbinarydataasparameters.Cursorscanalso beusedtoupdate database tables.
TheObject InterfaceforC++encapsulatescursorfunctionalityintotheITCursor
class.Thefollowingexcerptsfromthecursupd.cppexampleillustratetheuseof
ITCursor.
1. Touseacursor,theapplication createsaninstance ofITCursorontheopened
connection.
ITCursor cursor(conn);
2. Thecursorisopenedina transaction.ThepreparationoftheSELECTstatement
createsstatementparameters.
conn.SetTransaction(ITConnection::Begin);
if(!cursor.Prepare("select b from bar where b < ?::integer;")) {
Iftheapplicationdoesnotspecifyaparametertype namelist,default
parametertypesareused(see“ITStatement”onpage5-20).Createdparameters haveNULLvalues.
3. Whentheapplication needstoset aparametervalue, itobtainstheparameter’s ITValue*throughthecalltotheParam() function.
ITValue *par = cursor.Param(0); if(!par)
Theapplication cancalltheNumParams()functiontoobtainthenumberof parameters.
4. Theapplication setstheparametervalue usingITValue::FromPrintable().
if(!par->FromPrintable("3")) {
Alternatively,theapplicationcouldobtaintherequiredinterface bycalling
QueryInterface()andusetheupdatefunctionsprovidedbytheinterface. 5. Afterallparametervaluesareset,theapplicationopens thecursorwiththe
flags representingthesumofITCursor::Flagsvalues.
if(!cursor.Open(0, "bar")) {
By default,thecursorisopenedasupdateableandnonscrollable.Thecursor cannotbeopenedasupdateableand scrollableat thesame time.Ifthe application usesthecursor’sUpdateCurrent()orDeleteCurrent()functions,it needstoprovidethenameofthetablethatthecursoriscreatedonasa second argument ofOpen().
6. Theapplication canuseafetch functiontofindtherowfromthecursor.The
fetchfunction acceptsa pointertotheouterunknowninterfacefordelegation (formoredetailsaboutdelegation,seepage4-12).Thepointerisnullby default.
Thefetch functioncanperformthepositionalfetch.Ifthecursorwasnot openedasscrollable,positionalfetchwillfail.Theapplication cancallthe
IsScrollable() functiontocheck whetherthecursorisscrollable.The fetch function returnsthepointertotheITValueinterfaceoftheretrievedrow.The
NextRow()function returnsthepointertotheITRowinterface ofthatrow.
ITRow *row;
while(row = cursor.NextRow())
{
ITValue *col = row->Column(0); if(!col)
{
cerr << "Couldn’t get the column from the cursor’s row" << endl; return -1;
}
cout << "Column 0 was " << col->Printable() << endl;
Thefollowingexcerptsfromthecurstst.cppexampleprogramillustratetheuse ofa scrollablecursor.
a. Fetchrowsfromthebeginningtotheendoftheresultset.
cout << "FORWARDS" << endl;
while ((rowValue = cursor.Fetch()) != NULL) {
rowcount++;
cout << rowValue->Printable() << endl; rowValue->Release();
}
b. Fetchrowsfromtheendtothebeginningoftheresultset.
cout << "BACKWARDS" << endl; for (;;)
{
if (!(row = cursor.NextRow(0, ITPositionPrior))) break;
rowcount++;
cout << row->Printable() << endl; row->Release();
}
c. Fetcheverysecondrowfromthebeginningtotheendoftheresultset.
cout << "EVERY SECOND" << endl; for (;;)
{
if (!(row = cursor.NextRow(0, ITPositionRelative, 2 ))) break;
rowcount++;
cout << row->Printable() << endl; row->Release();
}
d. Fetchthethirdrowfromtheresultset.
cout << "THIRD" << endl;
row = cursor.NextRow(0, ITPositionAbsolute, 3); if (row != NULL)
{
rowcount++;
cout << row->Printable() << endl; row->Release();
}
e. Fetchthefirst rowoftheresultset.
cout << "FIRST" << endl;
row = cursor.NextRow(0, ITPositionFirst); if (row != NULL)
{
rowcount++;
cout << row->Printable() << endl; row->Release();
}
cout << "LAST" << endl;
row = cursor.NextRow(0, ITPositionLast); if (row != NULL)
{
rowcount++;
cout << row->Printable() << endl; row->Release();
}
g. Fetchthe500throw fromtheresult set.
cout << "500th" << endl;
row = cursor.NextRow(0, ITPositionAbsolute, 500); if (row != NULL)
{
rowcount++;
cout << row->Printable() << endl; row->Release();
}
ThecursormodelintheObjectInterfaceforC++adherestothefollowing rules:
v Whenthecursorisfirstopened, itispositioned beforethefirstrow.
Whenyouretrievearow,thecursoradvancestotherowandthen retrievesthedata.
v
Whenacursorreachesthelastrowina setithasscrolledthroughanda
subsequentfetch returnsNULL,thecursorremainspositionedonthelast row.Ifyoureversethedirectionofthesubsequentfetchtoretrievethe previousrow,thenthesecond-to-lastrow willbe fetched.
v Ifyoufetchfromthelastrowuptothefirstrow untilthereare nomore
rows,thecursorwillremainpositioned onthefirst row.
v Cursorsdo notwraparound.For example,youcannotopena cursorand
retrievetheprevious rowinanattempttowraparoundtothelast row. Similarly,youcannotwraparoundfromthelastrowto thefirst row. v WhenusingITPositionAbsolutetopositionthecursor,use1forthefirst
row.
7. Theapplication canmodify thecolumns ofthefetchedrow using,forexample, FromPrintable().
if(!colduprow->FromPrintable("2"))
{
cerr << "Couldn’t set the column value" << endl; return -1;
}
else
{
cout << "Column 0 is now " << colduprow->Printable() << endl; }
8. Ifthecursorwasopened asupdateable,theapplicationcanupdatethecurrent
rowusingtheUpdateCurrent()function,ordeleteitusingDeleteCurrent(). Theapplication canusetheIsUpdatable()functiontocheck whetherthecursor isupdatable.Calling UpdateCurrent()causesmodificationsthathavebeen madetothecurrentrowtobe reflectedinthedatabase(thecurrentrowbeing therowthatwasmostrecentlyreturnedbytheFetch()ortheNextRow()
function).
if(!cursor.UpdateCurrent()) {
cerr << "Could not update the current row" << endl; return -1;
}
Notethatiftheapplication fetchestherow,holdsitsreference,andthen fetches anotherrow,thefirstrow isnolongercurrent,andupdatestoitarenotreflected in thedatabase whentheapplication callsUpdateCurrent().
The applicationcanclosethecursor,modifyparameters,and reopenthecursor. Reopeninga cursorclosesthecurrentone.Parametervaluesthathavenotbeen reset staythesame.
Aftertheapplicationfinisheswith thecursor,itdropsthecursorusingtheDrop()
function. ThesameinstanceofITCursor canbeusedtoprepareanothercursorby calling Prepare(),whichhastheeffectof callingDrop()forthecurrentcursor.
Using
the
Large
Object
Manager
The ITLargeObjectManagerclassperformssimpleoperationsonlargeobjectssuch ascreating,opening,reading,andseeking.
The functionalityof theITLargeObjectManager classisonlysupportedwith Dynamic Serverdatabases.
Generally,this classisnotuseddirectly,butisincludedasamemberofsomeclass thatimplements adatabase typethathasoneormore largeobjectswithinit.For instance,a serversounddatatype mayhavea largeobjectthatholdsthedigitized waveform.TheC++typeimplementationmustknowhowtoread thatlargeobject. By usinganITLargeObjectManagerasa member,theimplementorofthedata type canleveragecodefromtheITLargeObjectManagerclassimplementation. The applicationcanuseITLargeObjectManager::CreateLO()tocreateanew large object. Itcanthengetthehandleofthenewlycreatedlargeobjectineither textor binary formusingITLargeObjectManager::HandleText()or
ITLargeObjectManager::Handle()andinsert itintoa table.Theseoperationsmust occur withinthesametransaction; otherwisethelargeobjectfallspreytogarbage collection.
Youcanperformoperations onlargeobjectswithin afetchedroweventhoughthe connection isstill checkedout(locked).Aconnectionischeckedoutafterthe
ITQuery::ExecForIteration()methodreturnsmultiplerowsintheresultset.It remainscheckedoutuntil eitherthelast rowintheresultsethasbeenfetchedwith
ITQuery::NextRow()orthequeryprocessinghasbeenterminatedbycalling
ITQuery::Finish().Whilea connectionischeckedout,nootherquerycanbe executedonthatconnection.
The followingexcerpt fromloadtab.cppillustratestheuseof the
ITLargeObjectManager.
TousetheITLargeObjectManager,theapplicationcreatesan instanceofitonan opened connectionobject.TheCreateLO()methodcreates thelargeobjectandsets thehandleoftheITLargeObjectManagertothenewlargeobject.
The Write()methodwritesthestringpointed tobypdb intothelargeobjectfrom thecurrentposition(inthiscasefromthebeginningofthestring).
Finally,thestatementparameterissettothevalueof thelargeobjecthandle, retrievedintextformatbycallingITLargeObj.
ITLargeObjectManager lobMgr(conn);
lobMgr.CreateLO();
if (!param->FromPrintable(lobMgr.HandleText()))
{ cerr
<< "Could not set LOB parameter "
<< paramno << " to ’" << pdb << "’" << endl; return -1; } } else if(param->TypeOf().Name().Equal("byte")) { ITDatum *pdatum = 0;
param->QueryInterface(ITDatumIID, (void **)&pdatum); if(!pdatum)
{
cerr << "BYTE type does not expose ITDatum???" << endl; return -1;
}
if(!pdatum->SetData(pdb, pdbpos, 0)) {
cerr << "SetData() for BYTE failed" << endl; return -1;
}
pdatum->Release(); }
else if (null == TRUE)
{
if (!param->SetNull()) {
cerr << "Could not set parameter " << paramno << " to null" << endl; return -1;
} }
Using
ITRoutineManager
ITRoutineManager providesanalternativewaytoexecuteserverroutines. ThefunctionalityoftheITRoutineManager classisonlysupportedwithDynamic Server databases.
WhenusingITRoutineManager,aconnectiondoesnothavetobecheckedoutto get orexecutearoutine(anda valueobject, therefore,canuseit),and the
executionoftheroutinecommencesfastersincethereisnoSQLtoparse.
Thefollowingexcerptsfromroutine.cppillustratetheuseofITRoutineManager. 1. TouseITRoutineManager,theapplication createsaninstance ofitonanopen
connectionobject.
ITRoutineManager routine(conn);
2. TheGetRoutine()methodretrievesthefunction descriptorforthefunction
whosesignatureispassedasanargument.
ITBool bret = routine.GetRoutine("function sum(int,int)");
3. Theapplication setsparameter valuesusingITValue::FromPrintable().
val = routine.Param(0); val->FromPrintable("1"); val->Release();
Itcouldalso setparametervaluesusingITRoutineManager::SetParam(). 4. TheroutineisexecutedwithExecForValue(),whichreturnsapointerto
ITValuecorrespondingtothereturnvalue oftheroutine.
val2 = routine.ExecForValue();
5. ARelease()callreleasestheITValueinstance.
val2->Release(); }
Chapter
3.
Accessing
Data
Values
AccessingDataValues . . . 3-1
ValueObjectManagement . . . 3-2
TheITValueInterface . . . 3-3
TheITConversionsInterface . . . 3-4
TheITDatumInterface . . . 3-4
TheITDateTimeInterface . . . 3-4
TheITLargeObjectInterface. . . 3-5 TheITErrorInfoInterface . . . 3-5
TheITRowInterface . . . 3-6
TheITSetInterface. . . 3-6 TheITContainerInterface . . . 3-7
TheITContainCvtInterface . . . 3-8
In
This
Chapter
Thischapterdiscussesthespecific valueinterfacesindetail,andshowshow to modify valueobjectsandextractinformationthroughthevalue interfacesintohost variablesinyour application.
Accessing
Data
Values
Acolumnvalue inadatabase canbe anatomicSQL92type (suchasinteger or
varchar)or,inIBMInformixDynamic Serverdatabases,anyofthefollowing extended datatypes:
v Anopaquedatatype,suchasthosesuppliedwith IBMInformixDynamic Server
DataBlademodules (forexamplePntforspatialpoints ordocfordocuments) v Rowtypes, includingtypesthatuseinheritance
v Collectiontypes,suchasSet,List,andMultiset
v
Largeobjecttypes
Toenable applicationstointeractuniformlywith valueobjects,allvalue objects presenttheITValueinterface.Valueobjectscanexposeadditionalinterfacesto presentdifferentbehaviorstotheapplication.Forinstance,a valueobject
representing asetcanexposeacontainerinterface suchasITSetor ITContainer.
The followingtable liststheDynamicServervalue objectinterfaces.
Interface Description
ITRow Rowobjectinterface(forexample,avectorofnamedattributes,such asarow)
ITContainCvt Containerobjectwithmembersthatcanbeconvertedtoandfrom C++types
ITContainer Containerobjectwithintegerindex-basedaccess
ITConversions ObjectthatcanbeconvertedtoandfromC++basetypes ITDateTime Dateandtimeinformation
ITDatum Underlyingdataaccess ITErrorInfo Errorinformation
ITEssential Baseinterface.Supportsreferencecountingandinterfacequerying ITLargeObject Largeobject.Supportsfileread-writesemantics
ITSet Containerobjectwithrandomaccess ITValue Basicvalueobjectinterface
For atableshowing howtheserverdatatypesare supportedintheIBMInformix Object InterfaceforC++,refertoAppendixA.
Value
Object
Management
All valueobjectinterfacesarederivedfromthebaseinterface,ITEssential.This interface definesbasicreferencecountingmethods(AddRefand Release)on objects.Referencecountingenablesapplicationstoensurethatthereferencesto objectsremainvalid.
The ITEssential::QueryInterfacemethodenablesanapplication todetermine whetheran objectsupportsaspecified interface,eitheronedefinedbytheObject InterfaceforC++ora custominterfacecreatedbya DataBladedeveloper.Ifthe interface issupported, ITEssential::QueryInterfaceprovidesapointertothe interface andreturnsIT_QUERYINTERFACE_SUCCESS.Iftheinterface isnot supported, ITEssential::QueryInterfacereturnsIT_QUERYINTERFACE_FAILED. For alistofinterface identifiersfortheinterfacesprovided bytheObjectInterface for C++,referto“ITEssential”onpage6-4.
Becauseall valueobjectinterfacesderive fromITEssential,yourapplicationcan obtaina pointertoanyinterfacesupportedbythevalueobjectfromanyother interface supportedbytheobject.
The tabcnt.cppexamplereadsan integervalue (thenumber oftablesinthe database) fromtheserverintoa valueobject, thenconverts itintoahostvariable usingtheITConversionsinterface.Thefollowingcodeexcerptsillustratetheuseof theQueryInterfacemethodinthetabcnt.cppexample:
1. Issuethequerythatreturnsthenumberoftables.
ITRow *row;
row = q.ExecOneRow("select unique count(*) from systables where tabname in (’systables’, ’syscolumns’,
’sysviews’);");
2. Extractthevalueobjectfromthefirst columnoftheresultrow.
3. ExtractanITConversionsinterface fromtheobject.
ITConversions *c;
// Extract an interface. The return code IT_QUERYINTERFACE_SUCCESS // should be used for compatibility reasons.
if (v->QueryInterface(ITConversionsIID, (void **) &c)
== IT_QUERYINTERFACE_SUCCESS)
{
4. Convertthevalueintoa hostvariable,printthevalue,andrelease the
conversionsinterface.
int numtabs;
if (c->ConvertTo(numtabs)) {
cout << "Number of rows in the query was: " << numtabs << endl;
}
// Release the conversions interface c->Release();
5. ReleasetheITValueand ITRowinterfaces.
v->Release(); row->Release();
Objectsarecreatedwith areference countof1 whentheyarereturnedtothe application. Whenyour applicationcallsITEssential::QueryInterfaceandobtainsa pointer toaninterface,anotherreferencetotheobjectisreturnedtothe
application, andthereferencecountisincremented.Whentheapplicationno longerrequiresaninterface,itmust calltheRelease methodtoreleasethe interface.
The
ITValue
Interface
TheITValueinterface definessimple comparisonandprintingmethodsonavalue objectandprovides accesstotheservertypeinformationofan object.All value objectsmust, ataminimum,exposeanITValueinterfaceoraninterface derived fromITValue.An objectcanexposeotherinterfacesaccessiblethrough the
ITEssential::QueryInterfacemethod.
TheITValue::TypeOf methodreturnsareferencetoan ITTypeInfoobject,from whichyour applicationcanextractinformationsuchasitsservertype,whetherit isa simpleorcollection type,itssize (fixedorvariable),andsoon.Formore details, referto“ITTypeInfo”onpage5-24.
Other ITValuemethodsenableyour applicationtoperform comparisonsto determinewhethertheobjectisequal to,greaterthan,or lessthananother object. Todeterminewhetherobjectsarecomparable, yourapplication cancallthe
ITValue::CompatibleTypemethod.TheITValue::CompatibleTypemethodis definedbytheimplementor ofavalue object.TheITValue::CompatibleType
method morelooselydefinescomparisonsthantheITValue::SameType method, enabling applicationstocomparevalueobjectsofdifferenttypes.
Two typesaresaidtobe compatibleif theymeetanyof thefollowingconditions: v Theyarethesametype.
v Theyarebuilt-intypesthatexposeITDateTime (date,datetime,interval).
v TheybothexposetheITConversions interface.
v TheyareDISTINCTfromthesametype.
v Theyarerow typeswith thesame columntypes.