tutorial: database communication in labview
TRANSCRIPT
UniversityCollegeofSoutheastNorway
http://home.hit.no/~hansha
DatabaseCommunication inLabVIEW
Hans-PetterHalvorsen,2016.10.31
2
PrefaceThisdocumentexplainsthebasicconceptsofadatabasesystemandhowtocommunicatewithadatabasefromLabVIEW.
YoushouldhavesomebasicknowledgeaboutLabVIEW,e.g.,the“AnIntroductiontoLabVIEW”training.Thisdocumentisavailablefordownloadathttp://home.hit.no/~hansha/.
InadditiontoLabVIEWProfessionalDevelopmentSystem,youneedtoinstallthe“LabVIEWDatabaseConnectivityToolkit”.
FormoreinformationaboutLabVIEWandDatabases,visitmyBlog:http://home.hit.no/~hansha/
Sometextinthisdocumentisbasedontextfromwww.wikipedia.organd“LabVIEWDatabaseConnectivityToolkitUserManual”.
iii
TableofContentsPreface......................................................................................................................................2
TableofContents.....................................................................................................................iii
1 IntroductiontoLabVIEW...................................................................................................1
1.1 Dataflowprogramming...............................................................................................1
1.2 Graphicalprogramming..............................................................................................1
1.3 Benefits.......................................................................................................................2
2 DatabaseSystems.............................................................................................................3
2.1 RDBMSComponents...................................................................................................3
2.2 Datawarehouse..........................................................................................................4
2.3 RelationalDatabase....................................................................................................4
2.4 Real-timedatabases...................................................................................................4
2.5 DatabaseManagementSystems................................................................................5
2.6 MDAC..........................................................................................................................5
2.6.1 ODBC...................................................................................................................5
2.6.2 OLEDB.................................................................................................................6
2.6.3 ADO(ActiveXDataObjects).................................................................................6
3 RelationalDatabases.........................................................................................................7
3.1 Tables..........................................................................................................................7
3.2 UniqueKeysandPrimaryKey.....................................................................................7
3.3 ForeignKey.................................................................................................................9
3.4 Views........................................................................................................................10
3.5 Functions..................................................................................................................10
iv TableofContents
Tutorial: Database Communication in LabVIEW
3.6 Storedprocedures....................................................................................................11
3.7 Triggers.....................................................................................................................11
4 StructuredQueryLanguage(SQL)...................................................................................13
4.1 Queries.....................................................................................................................13
4.2 Datamanipulation....................................................................................................14
4.3 Datadefinition..........................................................................................................15
4.4 Datatypes.................................................................................................................16
4.4.1 Characterstrings...............................................................................................16
4.4.2 Bitstrings...........................................................................................................16
4.4.3 Numbers............................................................................................................16
4.4.4 DateandTime...................................................................................................16
5 DatabaseModelling........................................................................................................17
5.1 ERDiagram...............................................................................................................17
5.2 MicrosoftVisio..........................................................................................................18
5.3 EXERCISES.....................................................................Error!Bookmarknotdefined.
6 MicrosoftSQLServer.......................................................................................................21
6.1 Introduction..............................................................................................................21
6.2 Requirements...........................................................................................................21
6.3 SQLServerExpress....................................................................................................21
6.4 AdventureWorks.......................................................................................................22
6.5 SQLServerManagementStudio...............................................................................22
6.6 CreateanewDatabase.............................................................................................23
6.7 Backup/Restore........................................................................................................24
6.8 ExampleDatabase....................................................................................................25
6.9 Exercises...................................................................................................................27
7 MicrosoftOfficeAccess...................................................................................................28
v TableofContents
Tutorial: Database Communication in LabVIEW
7.1 Introduction..............................................................................................................28
7.2 ExampleDatabase....................................................................................................28
7.3 Exercises...................................................................................................................30
8 ODBC...............................................................................................................................32
8.1 WhatisODBC?..........................................................................................................32
8.2 CreateanODBCConnectionin“ODBCDataSourceAdministrator”........................32
8.3 GetdataintoExcelusingyourODBCConnection.....................................................34
9 LabVIEWDatabaseConnectivityToolkit.........................................................................38
9.1 ConnecttotheDatabase..........................................................................................39
9.1.1 DSN....................................................................................................................40
9.1.2 UDL....................................................................................................................41
9.1.3 ConnectionString..............................................................................................42
9.2 ReadingDatafromtheDatabase..............................................................................42
9.3 WritingDatatotheDatabase...................................................................................46
9.4 CreatingandDroppingTables..................................................................................48
9.5 UsingtheDatabaseConnectivityToolkitUtilityVIs..................................................49
9.6 PerformingAdvancedDatabaseOperations............................................................50
10 CreatingandUsingTables...............................................................................................52
10.1 Exercises...................................................................................................................55
11 CreatingandUsingViews................................................................................................56
11.1 Exercises...................................................................................................................59
12 CreatingandusingStoredProcedures............................................................................60
12.1 Exercises...................................................................................................................62
13 CreatingandUsingTriggers............................................................................................63
13.1 Exercises...................................................................................................................66
14 CreatingandusingFunctions..........................................................................................67
vi TableofContents
Tutorial: Database Communication in LabVIEW
14.1 Exercises...................................................................................................................67
15 SQLToolkit......................................................................................................................68
15.1 Installation................................................................................................................68
1
1 IntroductiontoLabVIEWLabVIEW(shortforLaboratoryVirtualInstrumentationEngineeringWorkbench)isaplatformanddevelopmentenvironmentforavisualprogramminglanguagefromNationalInstruments.Thegraphicallanguageisnamed"G".OriginallyreleasedfortheAppleMacintoshin1986,LabVIEWiscommonlyusedfordataacquisition,instrumentcontrol,andindustrialautomationonavarietyofplatformsincludingMicrosoftWindows,variousflavorsofUNIX,Linux,andMacOSX.ThelatestversionofLabVIEWisversionLabVIEW2009,releasedinAugust2009.VisitNationalInstrumentsatwww.ni.com.
Thecodefileshavetheextension“.vi”,whichisaabbreviationfor“VirtualInstrument”.LabVIEWofferslotsofadditionalAdd-OnsandToolkits.
1.1 DataflowprogrammingTheprogramminglanguageusedinLabVIEW,alsoreferredtoasG,isadataflowprogramminglanguage.Executionisdeterminedbythestructureofagraphicalblockdiagram(theLV-sourcecode)onwhichtheprogrammerconnectsdifferentfunction-nodesbydrawingwires.Thesewirespropagatevariablesandanynodecanexecuteassoonasallitsinputdatabecomeavailable.Sincethismightbethecaseformultiplenodessimultaneously,Gisinherentlycapableofparallelexecution.Multi-processingandmulti-threadinghardwareisautomaticallyexploitedbythebuilt-inscheduler,whichmultiplexesmultipleOSthreadsoverthenodesreadyforexecution.
1.2 GraphicalprogrammingLabVIEWtiesthecreationofuserinterfaces(calledfrontpanels)intothedevelopmentcycle.LabVIEWprograms/subroutinesarecalledvirtualinstruments(VIs).EachVIhasthreecomponents:ablockdiagram,afrontpanel,andaconnectorpanel.ThelastisusedtorepresenttheVIintheblockdiagramsofother,callingVIs.Controlsandindicatorsonthefrontpanelallowanoperatortoinputdataintoorextractdatafromarunningvirtualinstrument.However,thefrontpanelcanalsoserveasaprogrammaticinterface.Thusavirtualinstrumentcaneitherberunasaprogram,withthefrontpanelservingasauserinterface,or,whendroppedasanodeontotheblockdiagram,thefrontpaneldefinesthe
2 IntroductiontoLabVIEW
Tutorial: Database Communication in LabVIEW
inputsandoutputsforthegivennodethroughtheconnectorpane.ThisimplieseachVIcanbeeasilytestedbeforebeingembeddedasasubroutineintoalargerprogram.
Thegraphicalapproachalsoallowsnon-programmerstobuildprogramssimplybydragginganddroppingvirtualrepresentationsoflabequipmentwithwhichtheyarealreadyfamiliar.TheLabVIEWprogrammingenvironment,withtheincludedexamplesandthedocumentation,makesitsimpletocreatesmallapplications.Thisisabenefitononeside,butthereisalsoacertaindangerofunderestimatingtheexpertiseneededforgoodquality"G"programming.Forcomplexalgorithmsorlarge-scalecode,itisimportantthattheprogrammerpossessanextensiveknowledgeofthespecialLabVIEWsyntaxandthetopologyofitsmemorymanagement.ThemostadvancedLabVIEWdevelopmentsystemsofferthepossibilityofbuildingstand-aloneapplications.Furthermore,itispossibletocreatedistributedapplications,whichcommunicatebyaclient/serverscheme,andarethereforeeasiertoimplementduetotheinherentlyparallelnatureofG-code.
1.3 BenefitsOnebenefitofLabVIEWoverotherdevelopmentenvironmentsistheextensivesupportforaccessinginstrumentationhardware.Driversandabstractionlayersformanydifferenttypesofinstrumentsandbusesareincludedorareavailableforinclusion.Thesepresentthemselvesasgraphicalnodes.Theabstractionlayersofferstandardsoftwareinterfacestocommunicatewithhardwaredevices.Theprovideddriverinterfacessaveprogramdevelopmenttime.ThesalespitchofNationalInstrumentsis,therefore,thatevenpeoplewithlimitedcodingexperiencecanwriteprogramsanddeploytestsolutionsinareducedtimeframewhencomparedtomoreconventionalorcompetingsystems.Anewhardwaredrivertopology(DAQmxBase),whichconsistsmainlyofG-codedcomponentswithonlyafewregistercallsthroughNIMeasurementHardwareDDK(DriverDevelopmentKit)functions,providesplatformindependenthardwareaccesstonumerousdataacquisitionandinstrumentationdevices.TheDAQmxBasedriverisavailableforLabVIEWonWindows,MacOSXandLinuxplatforms.
3
2 DatabaseSystemsAdatabaseisanintegratedcollectionoflogicallyrelatedrecordsorfilesconsolidatedintoacommonpoolthatprovidesdataforoneormoremultipleuses.
Onewayofclassifyingdatabasesinvolvesthetypeofcontent,forexample:bibliographic,full-text,numeric,andimage.Otherclassificationmethodsstartfromexaminingdatabasemodelsordatabasearchitectures.
Thedatainadatabaseisorganizedaccordingtoadatabasemodel.Therelationalmodelisthemostcommon.
ADatabaseManagementSystem(DBMS)consistsofsoftwarethatorganizesthestorageofdata.ADBMScontrolsthecreation,maintenance,anduseofthedatabasestoragestructuresoforganizationsandoftheirendusers.Itallowsorganizationstoplacecontroloforganization-widedatabasedevelopmentinthehandsofDatabaseAdministrators(DBAs)andotherspecialists.Inlargesystems,aDBMSallowsusersandothersoftwaretostoreandretrievedatainastructuredway.
Databasemanagementsystemsareusuallycategorizedaccordingtothedatabasemodelthattheysupport,suchasthenetwork,relationalorobjectmodel.Themodeltendstodeterminethequerylanguagesthatareavailabletoaccessthedatabase.OnecommonlyusedquerylanguagefortherelationaldatabaseisSQL,althoughSQLsyntaxandfunctioncanvaryfromoneDBMStoanother.AgreatdealoftheinternalengineeringofaDBMSisindependentofthedatamodel,andisconcernedwithmanagingfactorssuchasperformance,concurrency,integrity,andrecoveryfromhardwarefailures.Intheseareastherearelargedifferencesbetweenproducts.
2.1 RDBMSComponentsARelationalDatabaseManagementSystem(DBMS)consistsofthefollowingcomponents:
• Interfacedrivers-Auserorapplicationprograminitiateseitherschemamodificationorcontentmodification.ThesedriversarebuiltontopofSQL.Theyprovidemethodstopreparestatements,executestatements,fetchresults,etc.AnimportantexampleistheODBCdriver.
• SQLengine-ThiscomponentinterpretsandexecutestheSQLquery.Itcomprisesthreemajorcomponents(compiler,optimizer,andexecutionengine).
4 2
Tutorial: Database Communication in LabVIEW
• Transactionengine-Transactionsaresequencesofoperationsthatreadorwritedatabaseelements,whicharegroupedtogether.
• Relationalengine-RelationalobjectssuchasTable,Index,andReferentialintegrityconstraintsareimplementedinthiscomponent.
• Storageengine-Thiscomponentstoresandretrievesdatarecords.Italsoprovidesamechanismtostoremetadataandcontrolinformationsuchasundologs,redologs,locktables,etc.
2.2 DatawarehouseAdatawarehousestoresdatafromcurrentandpreviousyears—dataextractedfromthevariousoperationaldatabasesofanorganization.Itbecomesthecentralsourceofdatathathasbeenscreened,edited,standardizedandintegratedsothatitcanbeusedbymanagersandotherend-userprofessionalsthroughoutanorganization.
2.3 RelationalDatabaseArelationaldatabasematchesdatausingcommoncharacteristicsfoundwithinthedataset.Theresultinggroupsofdataareorganizedandaremucheasierforpeopletounderstand.
Forexample,adatasetcontainingallthereal-estatetransactionsinatowncanbegroupedbytheyearthetransactionoccurred;oritcanbegroupedbythesalepriceofthetransaction;oritcanbegroupedbythebuyer'slastname;andsoon.
Suchagroupingusestherelationalmodel(atechnicaltermforthisisschema).Hence,suchadatabaseiscalleda"relationaldatabase."
Thesoftwareusedtodothisgroupingiscalledarelationaldatabasemanagementsystem.Theterm"relationaldatabase"oftenreferstothistypeofsoftware.
Relationaldatabasesarecurrentlythepredominantchoiceinstoringfinancialrecords,manufacturingandlogisticalinformation,personneldataandmuchmore.
Strictly,arelationaldatabaseisacollectionofrelations(frequentlycalledtables).
2.4 Real-timedatabasesAreal-timedatabaseisaprocessingsystemdesignedtohandleworkloadswhosestatemaychangeconstantly.Thisdiffersfromtraditionaldatabasescontainingpersistentdata,mostlyunaffectedbytime.Forexample,astockmarketchangesrapidlyanddynamically.Real-time
5 2
Tutorial: Database Communication in LabVIEW
processingmeansthatatransactionisprocessedfastenoughfortheresulttocomebackandbeactedonrightaway.Real-timedatabasesareusefulforaccounting,banking,law,medicalrecords,multi-media,processcontrol,reservationsystems,andscientificdataanalysis.Ascomputersincreaseinpowerandcanstoremoredata,real-timedatabasesbecomeintegratedintosocietyandareemployedinmanyapplications
2.5 DatabaseManagementSystemsThereareDatabaseManagementSystems(DBMS),suchas:
• MicrosoftSQLServer• Oracle• Sybase• dBase• MicrosoftAccess• MySQLfromSunMicrosystems(Oracle)• DB2fromIBM• etc.
ThisdocumentwillfocusonMicrosoftAccessandMicrosoftSQLServer.
2.6 MDACTheMicrosoftDataAccessComponents(MDAC)istheframeworkthatmakesitpossibletoconnectandcommunicatewiththedatabase.MDACincludesthefollowingcomponents:
• ODBC(OpenDatabaseConnectivity)• OLEDB• ADO(ActiveXDataObjects)
MDACalsoinstallsseveraldataprovidersyoucanusetoopenaconnectiontoaspecificdatasource,suchasanMSAccessdatabase.
2.6.1 ODBC
OpenDatabaseConnectivity(ODBC)isanativeinterfacethatisaccessedthroughaprogramminglanguagethatcanmakecallsintoanativelibrary.InMDACthisinterfaceisdefinedasaDLL.Aseparatemoduleordriverisneededforeachdatabasethatmustbeaccessed.
6 2
Tutorial: Database Communication in LabVIEW
2.6.2 OLEDB
OLEallowsMDACapplicationsaccesstodifferenttypesofdatastoresinauniformmanner.Microsofthasusedthistechnologytoseparatetheapplicationfromthedatastorethatitneedstoaccess.Thiswasdonebecausedifferentapplicationsneedaccesstodifferenttypesandsourcesofdata,anddonotnecessarilyneedtoknowhowtoaccesstechnology-specificfunctionality.Thetechnologyisconceptuallydividedintoconsumersandproviders.Theconsumersaretheapplicationsthatneedaccesstothedata,andtheprovideristhesoftwarecomponentthatexposesanOLEDBinterfacethroughtheuseoftheComponentObjectModel(orCOM).
2.6.3 ADO(ActiveXDataObjects)
ActiveXDataObjects(ADO)isahighlevelprogramminginterfacetoOLEDB.Itusesahierarchicalobjectmodeltoallowapplicationstoprogrammaticallycreate,retrieve,updateanddeletedatafromsourcessupportedbyOLEDB.ADOconsistsofaseriesofhierarchicalCOM-basedobjectsandcollections,anobjectthatactsasacontainerofmanyotherobjects.AprogrammercandirectlyaccessADOobjectstomanipulatedata,orcansendanSQLquerytothedatabaseviaseveralADOmechanisms.
7
3 RelationalDatabasesArelationaldatabasematchesdatausingcommoncharacteristicsfoundwithinthedataset.Theresultinggroupsofdataareorganizedandaremucheasierforpeopletounderstand.
Forexample,adatasetcontainingallthereal-estatetransactionsinatowncanbegroupedbytheyearthetransactionoccurred;oritcanbegroupedbythesalepriceofthetransaction;oritcanbegroupedbythebuyer'slastname;andsoon.
Suchagroupingusestherelationalmodel(atechnicaltermforthisisschema).Hence,suchadatabaseiscalleda"relationaldatabase."
Thesoftwareusedtodothisgroupingiscalledarelationaldatabasemanagementsystem.Theterm"relationaldatabase"oftenreferstothistypeofsoftware.
Relationaldatabasesarecurrentlythepredominantchoiceinstoringfinancialrecords,manufacturingandlogisticalinformation,personneldataandmuchmore.
3.1 TablesThebasicunitsinadatabasearetablesandtherelationshipbetweenthem.Strictly,arelationaldatabaseisacollectionofrelations(frequentlycalledtables).
3.2 UniqueKeysandPrimaryKey
8 RelationalDatabases
Tutorial: Database Communication in LabVIEW
Inrelationaldatabasedesign,auniquekeyorprimarykeyisacandidatekeytouniquelyidentifyeachrowinatable.Auniquekeyorprimarykeycomprisesasinglecolumnorsetofcolumns.Notwodistinctrowsinatablecanhavethesamevalue(orcombinationofvalues)inthosecolumns.Dependingonitsdesign,atablemayhavearbitrarilymanyuniquekeysbutatmostoneprimarykey.
Auniquekeymustuniquelyidentifyallpossiblerowsthatexistinatableandnotonlythecurrentlyexistingrows.ExamplesofuniquekeysareSocialSecuritynumbersorISBNs.
Aprimarykeyisaspecialcaseofuniquekeys.ThemajordifferenceisthatforuniquekeystheimplicitNOTNULLconstraintisnotautomaticallyenforced,whileforprimarykeysitisenforced.Thus,thevaluesinuniquekeycolumnsmayormaynotbeNULL.Anotherdifferenceisthatprimarykeysmustbedefinedusinganothersyntax.
Primarykeysaredefinedwiththefollowingsyntax:
CREATE TABLE table_name ( id_col INT, col2 CHARACTER VARYING(20), ... CONSTRAINT tab_pk PRIMARY KEY(id_col), ... )
Iftheprimarykeyconsistsonlyofasinglecolumn,thecolumncanbemarkedassuchusingthefollowingsyntax:
CREATE TABLE table_name ( id_col INT PRIMARY KEY, col2 CHARACTER VARYING(20), ... )
Thedefinitionofuniquekeysissyntacticallyverysimilartoprimarykeys.
Likewise,uniquekeyscanbedefinedaspartoftheCREATETABLESQLstatement.
CREATE TABLE table_name ( id_col INT, col2 CHARACTER VARYING(20), key_col SMALLINT, ... CONSTRAINT key_unique UNIQUE(key_col), ... )
Oriftheuniquekeyconsistsonlyofasinglecolumn,thecolumncanbemarkedassuchusingthefollowingsyntax:
CREATE TABLE table_name (
9 RelationalDatabases
Tutorial: Database Communication in LabVIEW
id_col INT PRIMARY KEY, col2 CHARACTER VARYING(20), ... key_col SMALLINT UNIQUE, ... )
3.3 ForeignKeyInthecontextofrelationaldatabases,aforeignkeyisareferentialconstraintbetweentwotables.Theforeignkeyidentifiesacolumnorasetofcolumnsinonetablethatreferstoacolumnorsetofcolumnsinanothertable.Thecolumnsinthereferencingtablemustbetheprimarykeyorothercandidatekeyinthereferencedtable.Thevaluesinonerowofthereferencingcolumnsmustoccurinasinglerowinthereferencedtable.Thus,arowinthereferencingtablecannotcontainvaluesthatdon'texistinthereferencedtable.Thiswayreferencescanbemadetolinkinformationtogetheranditisanessentialpartofdatabasenormalization.Multiplerowsinthereferencingtablemayrefertothesamerowinthereferencedtable.Mostofthetime,itreflectstheone(mastertable,orreferencedtable)tomany(childtable,orreferencingtable)relationship.
Thereferencingandreferencedtablemaybethesametable,i.e.theforeignkeyrefersbacktothesametable.Suchaforeignkeyisknownasself-referencingorrecursiveforeignkey.
Atablemayhavemultipleforeignkeys,andeachforeignkeycanhaveadifferentreferencedtable.Eachforeignkeyisenforcedindependentlybythedatabasesystem.Therefore,cascadingrelationshipsbetweentablescanbeestablishedusingforeignkeys.
Improperforeignkey/primarykeyrelationshipsornotenforcingthoserelationshipsareoftenthesourceofmanydatabaseanddatamodelingproblems.
ForeignkeyscanbedefinedaspartoftheCREATETABLESQLstatement.
CREATE TABLE table_name ( id INTEGER PRIMARY KEY, col2 CHARACTER VARYING(20), col3 INTEGER, ... CONSTRAINT col3_fk FOREIGN KEY(col3) REFERENCES other_table(key_col), ... )
Iftheforeignkeyisasinglecolumnonly,thecolumncanbemarkedassuchusingthefollowingsyntax:
CREATE TABLE table_name ( id INTEGER PRIMARY KEY, col2 CHARACTER VARYING(20),
10 RelationalDatabases
Tutorial: Database Communication in LabVIEW
col3 INTEGER REFERENCES other_table(column_name), ... )
3.4 ViewsIndatabasetheory,aviewconsistsofastoredqueryaccessibleasavirtualtablecomposedoftheresultsetofaquery.Unlikeordinarytablesinarelationaldatabase,aviewdoesnotformpartofthephysicalschema:itisadynamic,virtualtablecomputedorcollatedfromdatainthedatabase.Changingthedatainatablealtersthedatashowninsubsequentinvocationsoftheview.
Viewscanprovideadvantagesovertables:
• Viewscanrepresentasubsetofthedatacontainedinatable • Viewscanjoinandsimplifymultipletablesintoasinglevirtualtable • Viewscanactasaggregatedtables,wherethedatabaseengineaggregatesdata
(sum,averageetc)andpresentsthecalculatedresultsaspartofthedata • Viewscanhidethecomplexityofdata;forexampleaviewcouldappearasSales2000
orSales2001,transparentlypartitioningtheactualunderlyingtable • Viewstakeverylittlespacetostore;thedatabasecontainsonlythedefinitionofa
view,notacopyofallthedataitpresents • Viewscanlimitthedegreeofexposureofatableortablestotheouterworld
Syntax:
CREATE VIEW <ViewName> AS …
3.5 FunctionsInSQLdatabases,auser-definedfunctionprovidesamechanismforextendingthefunctionalityofthedatabaseserverbyaddingafunctionthatcanbeevaluatedinSQLstatements.TheSQLstandarddistinguishesbetweenscalarandtablefunctions.Ascalarfunctionreturnsonlyasinglevalue(orNULL),whereasatablefunctionreturnsa(relational)tablecomprisingzeroormorerows,eachrowwithoneormorecolumns.
User-definedfunctionsinSQLaredeclaredusingtheCREATEFUNCTIONstatement.
Syntax:
CREATE FUNCTION <FunctionName> (@Parameter1 <datatype>, @ Parameter2 <datatype>,
11 RelationalDatabases
Tutorial: Database Communication in LabVIEW
…) RETURNS <datatype> AS …
3.6 StoredproceduresAstoredprocedureisexecutablecodethatisassociatedwith,andgenerallystoredin,thedatabase.Storedproceduresusuallycollectandcustomizecommonoperations,likeinsertingatupleintoarelation,gatheringstatisticalinformationaboutusagepatterns,orencapsulatingcomplexbusinesslogicandcalculations.Frequentlytheyareusedasanapplicationprogramminginterface(API)forsecurityorsimplicity.
Storedproceduresarenotpartoftherelationaldatabasemodel,butallcommercialimplementationsincludethem.
Storedproceduresarecalledorusedwiththefollowingsyntax:
CALL procedure(…)
or
EXECUTE procedure(…)
Storedprocedurescanreturnresultsets,i.e.theresultsofaSELECTstatement.Suchresultsetscanbeprocessedusingcursorsbyotherstoredproceduresbyassociatingaresultsetlocator,orbyapplications.Storedproceduresmayalsocontaindeclaredvariablesforprocessingdataandcursorsthatallowittoloopthroughmultiplerowsinatable.ThestandardStructuredQueryLanguageprovidesIF,WHILE,LOOP,REPEAT,CASEstatements,andmore.Storedprocedurescanreceivevariables,returnresultsormodifyvariablesandreturnthem,dependingonhowandwherethevariableisdeclared.
3.7 TriggersAdatabasetriggerisproceduralcodethatisautomaticallyexecutedinresponsetocertaineventsonaparticulartableorviewinadatabase.Thetriggerismostlyusedforkeepingtheintegrityoftheinformationonthedatabase.Forexample,whenanewrecord(representinganewworker)addedtotheemployeestable,newrecordsshouldbecreatedalsointhetablesofthetaxes,vacations,andsalaries.
Thesyntaxisasfollows:
CREATE TRIGGER <TriggerName> ON <TableName>
12 RelationalDatabases
Tutorial: Database Communication in LabVIEW
FOR INSERT, UPDATE, DELETE AS …
13
4 StructuredQueryLanguage(SQL)
SQL(StructuredQueryLanguage)isadatabasecomputerlanguagedesignedformanagingdatainrelationaldatabasemanagementsystems(RDBMS).
4.1 QueriesThemostcommonoperationinSQListhequery,whichisperformedwiththedeclarativeSELECTstatement.SELECTretrievesdatafromoneormoretables,orexpressions.StandardSELECTstatementshavenopersistenteffectsonthedatabase.
Queriesallowtheusertodescribedesireddata,leavingthedatabasemanagementsystem(DBMS)responsibleforplanning,optimizing,andperformingthephysicaloperationsnecessarytoproducethatresultasitchooses.
AqueryincludesalistofcolumnstobeincludedinthefinalresultimmediatelyfollowingtheSELECTkeyword.Anasterisk("*")canalsobeusedtospecifythatthequeryshouldreturnallcolumnsofthequeriedtables.SELECTisthemostcomplexstatementinSQL,withoptionalkeywordsandclausesthatinclude:
• TheFROMclausewhichindicatesthetable(s)fromwhichdataistoberetrieved.TheFROMclausecanincludeoptionalJOINsubclausestospecifytherulesforjoiningtables.
• TheWHEREclauseincludesacomparisonpredicate,whichrestrictstherowsreturnedbythequery.TheWHEREclauseeliminatesallrowsfromtheresultsetforwhichthecomparisonpredicatedoesnotevaluatetoTrue.
• TheGROUPBYclauseisusedtoprojectrowshavingcommonvaluesintoasmallersetofrows.GROUPBYisoftenusedinconjunctionwithSQLaggregationfunctionsortoeliminateduplicaterowsfromaresultset.TheWHEREclauseisappliedbeforetheGROUPBYclause.
• TheHAVINGclauseincludesapredicateusedtofilterrowsresultingfromtheGROUPBYclause.BecauseitactsontheresultsoftheGROUPBYclause,aggregationfunctionscanbeusedintheHAVINGclausepredicate.
14 StructuredQueryLanguage(SQL)
Tutorial: Database Communication in LabVIEW
• TheORDERBYclauseidentifieswhichcolumnsareusedtosorttheresultingdata,andinwhichdirectiontheyshouldbesorted(optionsareascendingordescending).WithoutanORDERBYclause,theorderofrowsreturnedbyanSQLqueryisundefined.
Example:
ThefollowingisanexampleofaSELECTquerythatreturnsalistofexpensivebooks.ThequeryretrievesallrowsfromtheBooktableinwhichthepricecolumncontainsavaluegreaterthan100.00.Theresultissortedinascendingorderbytitle.Theasterisk(*)intheselectlistindicatesthatallcolumnsoftheBooktableshouldbeincludedintheresultset.
SELECT * FROM Book WHERE price > 100.00 ORDER BY title;
Theexamplebelowdemonstratesaqueryofmultipletables,grouping,andaggregation,byreturningalistofbooksandthenumberofauthorsassociatedwitheachbook.
SELECT Book.title,count(*) AS Authors FROM Book JOIN Book_author ON Book.isbn = Book_author.isbn GROUP BY Book.title
Exampleoutputmightresemblethefollowing:
Title Authors ------------------------------- SQL Examples and Guide 4 The Joy of SQL 1 An Introduction to SQL 2 Pitfalls of SQL 1
4.2 DatamanipulationTheDataManipulationLanguage(DML)isthesubsetofSQLusedtoadd,updateanddeletedata.
TheacronymCRUDreferstoallofthemajorfunctionsthatneedtobeimplementedinarelationaldatabaseapplicationtoconsideritcomplete.EachletterintheacronymcanbemappedtoastandardSQLstatement:
Operation SQL
Create INSERT
Read(Retrieve) SELECT
15 StructuredQueryLanguage(SQL)
Tutorial: Database Communication in LabVIEW
Update UPDATE
Delete(Destroy) DELETE
Example:INSERT
INSERTaddsrowstoanexistingtable,e.g.,:
INSERT INTO My_table field1, field2, field3) VALUES ('test', 'N', NULL)
Example:UPDATE
UPDATEmodifiesasetofexistingtablerows,e.g.,:
UPDATE My_table SET field1 = 'updated value' WHERE field2 = 'N'
Example:DELETE
DELETEremovesexistingrowsfromatable,e.g.,:
DELETE FROM My_table WHERE field2 = 'N'
4.3 DatadefinitionTheDataDefinitionLanguage(DDL)managestableandindexstructure.ThemostbasicitemsofDDLaretheCREATE,ALTER,RENAMEandDROPstatements:
• CREATEcreatesanobject(atable,forexample)inthedatabase. • DROPdeletesanobjectinthedatabase,usuallyirretrievably. • ALTERmodifiesthestructureanexistingobjectinvariousways—forexample,adding
acolumntoanexistingtable.
Example:CREATE
CreateaDatabaseTable
CREATE TABLE My_table ( my_field1 INT, my_field2 VARCHAR(50), my_field3 DATE NOT NULL, PRIMARY KEY (my_field1) )
16 StructuredQueryLanguage(SQL)
Tutorial: Database Communication in LabVIEW
4.4 DatatypesEachcolumninanSQLtabledeclaresthetype(s)thatcolumnmaycontain.ANSISQLincludesthefollowingdatatypes.
4.4.1 Characterstrings
• CHARACTER(n)orCHAR(n)—fixed-widthn-characterstring,paddedwithspacesasneeded
• CHARACTERVARYING(n)orVARCHAR(n)—variable-widthstringwithamaximumsizeofncharacters
• NATIONALCHARACTER(n)orNCHAR(n)—fixedwidthstringsupportinganinternationalcharacterset
• NATIONALCHARACTERVARYING(n)orNVARCHAR(n)—variable-widthNCHARstring
4.4.2 Bitstrings
• BIT(n)—anarrayofnbits • BITVARYING(n)—anarrayofuptonbits
4.4.3 Numbers
• INTEGERandSMALLINT • FLOAT,REALandDOUBLEPRECISION • NUMERIC(precision,scale)orDECIMAL(precision,scale)
4.4.4 DateandTime
• DATE • TIME • TIMESTAMP • INTERVAL
17
5 DatabaseModelling
5.1 ERDiagramInsoftwareengineering,anEntity-RelationshipModel(ERM)isanabstractandconceptualrepresentationofdata.Entity-relationshipmodelingisadatabasemodelingmethod,usedtoproduceatypeofconceptualschemaorsemanticdatamodelofasystem,oftenarelationaldatabase,anditsrequirementsinatop-downfashion.
Diagramscreatedusingthisprocessarecalledentity-relationshipdiagrams,orERdiagramsorERDsforshort.
[Wikipedia]
TherearemanyERdiagrammingtools.SomeoftheproprietaryERdiagrammingtoolsareERwin,EnterpriseArchitectandMicrosoftVisio.
MicrosoftSQLServerhasalsoabuilt-intoolforcreatingDatabaseDiagrams.
18 DatabaseModelling
Tutorial: Database Communication in LabVIEW
5.2 MicrosoftVisioMicrosoftVisioisadiagrammingprogramforcreatingdifferentkindsofdiagrams.VisiohaveatemplateforcreatingDatabaseModelDiagrams.
IntheDatabasemenuVisioofferslotsoffunctionalityregardingyourdatabasemodel.
19 DatabaseModelling
Tutorial: Database Communication in LabVIEW
“ReverseEngineering”istheoppositeprocedure,i.e.,extractionofadatabaseschemafromanexistingdatabaseintoadatabasemodelinMicrosoftVisio.
5.3 ExercisesExercise:DatabaseDiagram
CreatethefollowingtablesinanERDiagramusingMSVisio.
• CUSTOMERo CustomerId(PK)o FirstNameo LastNameo Addresso Phoneo PostCodeo PostAddress
• PRODUCTo ProductId(PK)o ProductNameo ProductDescriptiono Priceo ProductCode
• ORDERo OrderId(PK)o OrderNumber
20 DatabaseModelling
Tutorial: Database Communication in LabVIEW
o OrderDescriptiono CustomerId(FK)
• ORDER_DETAILo OrderDetailId(PK)o OrderId(FK)o ProductId(FK)
DatabaseDiagram:
21
6 MicrosoftSQLServer
6.1 IntroductionMicrosoftSQLServerisarelationalmodeldatabaseserverproducedbyMicrosoft.ItsprimaryquerylanguagesareT-SQLandANSISQL.
ThelatestversionisMicrosoftSQLServer2008.
MicrosoftSQLServerhomepage:www.microsoft.com/sqlserver
TheMicrosoftSQLServercomesindifferentversions,suchas:
• SQLServerDeveloperEdition• SQLServerEnterpriseEdition• SQLServerWebEdition• SQLServerExpressEdition• Etc.
TheSQLServerExpressEditionisafreely-downloadableand-distributableversion.
6.2 RequirementsInordertoinstallSQLServer2008,youneed:
• Microsoft.NETFramework3.5SP1• WindowsInstaller4.5• WindowsPowerShell1.0
Note:YoumusthaveadministrativerightsonthecomputertoinstallMicrosoftSQLServer2008.
6.3 SQLServerExpressTheSQLServerExpressEditionisafreely-downloadableand-distributableversion.
22 MicrosoftSQLServer
Tutorial: Database Communication in LabVIEW
However,theExpresseditionhasanumberoftechnicalrestrictionswhichmakeitundesirableforlarge-scaledeployments,including:
• Maximumdatabasesizeof4GBper.The4GBlimitappliesperdatabase(logfilesexcluded);butinsomescenariosuserscanaccessmoredatathroughtheuseofmultipleinterconnecteddatabases.
• SinglephysicalCPU,multiplecores • 1GBofRAM(runsonanysizeRAMsystem,butusesonly1GB)
SQLServerExpressoffersaGUItoolsfordatabasemanagementinaseparatedownloadandinstallationpackage,calledSQLServerManagementStudioExpress.
6.4 AdventureWorksTheAdventureWorksisasampleDatabasewithlotsofexamples,etc.
YoushouldinstallthissampleDatabasebecausesomeoftheexamplesinthisdocumentwillusetheAdventureWorksdatabase.
6.5 SQLServerManagementStudioSQLServerManagementStudioisaGUItoolincludedwithSQLServerforconfiguring,managing,andadministeringallcomponentswithinMicrosoftSQLServer.Thetoolincludesbothscripteditorsandgraphicaltoolsthatworkwithobjectsandfeaturesoftheserver.Asmentionedearlier,versionofSQLServerManagementStudioisalsoavailableforSQLServerExpressEdition,forwhichitisknownasSQLServerManagementStudioExpress.
AcentralfeatureofSQLServerManagementStudioistheObjectExplorer,whichallowstheusertobrowse,select,andactuponanyoftheobjectswithintheserver.Itcanbeusedtovisuallyobserveandanalyzequeryplansandoptimizethedatabaseperformance,amongothers.SQLServerManagementStudiocanalsobeusedtocreateanewdatabase,alteranyexistingdatabaseschemabyaddingormodifyingtablesandindexes,oranalyzeperformance.ItincludesthequerywindowswhichprovideaGUIbasedinterfacetowriteandexecutequeries.
23 MicrosoftSQLServer
Tutorial: Database Communication in LabVIEW
6.6 CreateanewDatabaseItisquitesimpletocreateanewdatabaseinMicrosoftSQLServer.Justright-clickonthe“Databases”nodeandselect“NewDatabase…”
24 MicrosoftSQLServer
Tutorial: Database Communication in LabVIEW
Therearelotsofsettingsyoumaysetregardingyourdatabase,buttheonlyinformationyoumustfillinisthenameofyourdatabase:
6.7 Backup/RestoreAnimportanttaskindatabasesystemsistotakebackupofthedatabasewithregularintervals,e.g.,duringthenightwhenthesystemisnotinuse.
DatabasebackupandRestore:
25 MicrosoftSQLServer
Tutorial: Database Communication in LabVIEW
6.8 ExampleDatabaseExamplesandexercisesinthistrainingarebasedonsomebasictables.TheExampleDatabaseconsistsofthefollowingTables:
26 MicrosoftSQLServer
Tutorial: Database Communication in LabVIEW
• CUSTOMERo CustomerId(PK)o FirstNameo LastNameo Addresso Phoneo PostCodeo PostAddress
• PRODUCTo ProductId(PK)o ProductNameo ProductDescriptiono Priceo ProductCode
• ORDERo OrderId(PK)o OrderNumbero OrderDescriptiono CustomerId(FK)
• ORDER_DETAILo OrderDetailId(PK)o OrderId(FK)o ProductId(FK)
27 MicrosoftSQLServer
Tutorial: Database Communication in LabVIEW
6.9 ExercisesExercise:NewDatabase
CreateanewDatabaseinMSSQLServercalledTEST_SQLSERVER.
Exercise:DatabaseDiagram
CreatethetablesintheExampleDatabaseusingtheDiagramDesignerToolinMicrosoftSQLServer.
Exercise:DatabaseScript
CreatethetablesintheExampleDatabaseTablesusingSQLCode.SavetheTablesasaSQLScriptfile(.sql).UseTheQueryToolinMicrosoftSQLServer.
Exercise:ODBC
CreateanODBCconnectionfortheDatabase.
28
7 MicrosoftOfficeAccess
7.1 IntroductionMicrosoftOfficeAccess,previouslyknownasMicrosoftAccess,isarelationaldatabasemanagementsystemfromMicrosoftthatcombinestherelationalMicrosoftJetDatabaseEnginewithagraphicaluserinterfaceandsoftwaredevelopmenttools.ItisamemberoftheMicrosoftOfficesuiteofapplicationsandisincludedintheProfessionalandhigherversionsforWindows.AccessstoresdatainitsownformatbasedontheAccessJetDatabaseEngine.
MicrosoftAccessisusedbyprogrammersandnon-programmerstocreatetheirownsimpledatabasesolutions.
MicrosoftAccessisafileserver-baseddatabase.Unlikeclient-serverrelationaldatabasemanagementsystems(RDBMS),e.g.,MicrosoftSQLServer,MicrosoftAccessdoesnotimplementdatabasetriggers,storedprocedures,ortransactionlogging.Alldatabasetables,queries,forms,reports,macros,andmodulesarestoredintheAccessJetdatabaseasasinglefile.ThismakesMicrosoftAccessusefulinsmallapplications,teaching,etc.becauseitiseasytomovefromonecomputertoanother.
7.2 ExampleDatabaseIwillpresentanexampledatabaseinMicrosoftAccess2007whichwillbeusedinsomeoftheexamplesandexercisesinthisdocument.
Thedatabaseconsistsofthefollowingtables:
• CUSTOMERo CustomerId(PK)o FirstNameo LastNameo Addresso Phoneo PostCodeo PostAddress
• PRODUCT
29 MicrosoftOfficeAccess
Tutorial: Database Communication in LabVIEW
o ProductId(PK)o ProductNameo ProductDescriptiono Priceo ProductCode
• ORDERo OrderId(PK)o OrderNumbero OrderDescriptiono CustomerId(FK)
• ORDER_DETAILo OrderDetailId(PK)o OrderId(FK)o ProductId(FK)
ODBCConnection:
AdministrativeTools→DataSources(ODBC)
30 MicrosoftOfficeAccess
Tutorial: Database Communication in LabVIEW
7.3 ExercisesExercise:Database
CreateanewDatabaseinMSAccesscalledTEST.
Exercise:DatabaseTables
31 MicrosoftOfficeAccess
Tutorial: Database Communication in LabVIEW
CreatethetablesintheExampleDatabaseTablesusingtheDiagramDesignerToolinMicrosoftSQLServer.
Exercise:ODBC
CreateanODBCconnectionfortheDatabase.
32
8 ODBC8.1 WhatisODBC?Incomputing,OpenDatabaseConnectivity(ODBC)providesastandardsoftwareAPImethodforusingdatabasemanagementsystems(DBMS).ThedesignersofODBCaimedtomakeitindependentofprogramminglanguages,databasesystems,andoperatingsystems.
8.2 CreateanODBCConnectionin“ODBCDataSourceAdministrator”
Followthesesteps:
AddanewDataSourceandselecttheSQLServerdriver:
TypeaNameforyourConnectionandyourSQLServerName.YoufindyourServernameasshownbelow:
33 ODBC
Tutorial: Database Communication in LabVIEW
SelectSQLServerauthenticationandtypeyoursapassword(SystemAdministrator). YoudefinedthepasswordforthesauserduringthesetupprocedureofSQLServer:
CompleteyourconfigurationandTestyourdatasourcetoseeifitsOK:
34 ODBC
Tutorial: Database Communication in LabVIEW
Ifyougetthismessageyouhavesucceeded:
8.3 GetdataintoExcelusingyourODBCConnection
ThepurposeistouseExcelasaclientandgetdataintoExcelfromyourSQLServer.
Step1:OpenExcelandgototheDatasection:
35 ODBC
Tutorial: Database Communication in LabVIEW
Step2:SelectyourODBCconnection
Step3:SelectyourTable(s)
36 ODBC
Tutorial: Database Communication in LabVIEW
Step4:InsertDataintoExcel
Theresultsshouldlooksomethinglikethis:
37 ODBC
Tutorial: Database Communication in LabVIEW
38
9 LabVIEWDatabaseConnectivityToolkit
LabVIEWoffersanadditionalToolkitcalled“LabVIEWDatabaseConnectivityToolkit”.Withthistoolkityoucancommunicatewithdifferentdatabases,suchasSQLServer,Oracle,etc.
FunctionsPalette:Connectivity→Database
ThefollowinglistdescribesthemainfeaturesoftheDatabaseConnectivityToolkit:
• WorkswithanyproviderthatadherestotheMicrosoftActiveXDataObject(ADO)standard.
• WorkswithanydatabasedriverthatcomplieswithODBCorOLEDB.• Maintainsahighlevelofportability.Inmanycases,youcanportanapplicationto
anotherdatabasebychangingtheconnectioninformationyoupasstotheDBToolsOpenConnectionVI.
• ConvertsdatabasecolumnvaluesfromnativedatatypestostandardDatabaseConnectivityToolkitdatatypes,furtherenhancingportability.
• PermitstheuseofSQLstatementswithallsupporteddatabasesystems,evennon-SQLsystems.
• IncludesVIstoretrievethenameanddatatypeofacolumnreturnedbyaSELECTstatement.
• Createstablesandselects,inserts,updates,anddeletesrecordswithoutusingSQLstatements.
39 LabVIEWDatabaseConnectivityToolkit
Tutorial: Database Communication in LabVIEW
Someofthetextinthischapterisbasedonthe“LabVIEWDatabaseConnectivityToolkitUserManual”.
9.1 ConnecttotheDatabaseBeforeyoucanaccessdatainatableorexecuteSQLstatements,youmustestablishaconnectiontoadatabase.Youmayusedifferentmethodsinordertoconnecttothedatabase:
• ODBCDataSourceName(DSN)• UniversalDataLink(UDL)• ConnectionString
Thesedifferentmethodsareexplainedbelow.
Forallofthesemethods,youwillusethesameVI:
Connectingtoadatabaseiswheremosterrorsoccurbecauseeachdatabasemanagementsystem(DBMS)usesdifferentparametersfortheconnectionanddifferentlevelsofsecurity.Thedifferentstandardsalsousedifferentmethodsofconnectingtodatabases.Forexample,ODBCusesDataSourceNames(DSN)fortheconnection,whereastheMicrosoftActiveXDataObject(ADO)standardusesUniversalDataLinks(UDL)fortheconnection.The“DBToolsOpenConnection.vi”VIsupportsallthesemethodsforconnectingtoadatabase.
Whenyouarefinishedwithreadingfromthedatabaseandwritingtothedatabase,youshouldalwaysclosetheConnection.Usethe“DBToolsCloseConnection.vi”.
40 LabVIEWDatabaseConnectivityToolkit
Tutorial: Database Communication in LabVIEW
9.1.1 DSN
ADSN(ODBCDataSourceName(DSN))isthenameofthedatasource,ordatabase,towhichyouareconnecting.TheDSNalsocontainsinformationabouttheODBCdriverandotherconnectionattributesincludingpaths,securityinformation,andread-onlystatusofthedatabase.TwomaintypesofDSNsexist:machineDSNsandfileDSNs.MachineDSNsareinthesystemregistryandapplytoallusersofthecomputersystemortoasingleuser.DSNsthatapplytoallusersofacomputersystemaresystemDSNs.DSNsthatapplytosingleusersareuserDSNs.AfileDSNisatextfilewitha.dsnextensionandisaccessibletoanyonewithproperpermissions.FileDSNsarenotrestrictedtoasingleuserorcomputersystem.UsetheODBCDataSourceAdministratortocreateandconfigureDSNs.
IntheControlPanel,AdministrativeTools,youfindtheODBCDataSourceAdministratortool.
41 LabVIEWDatabaseConnectivityToolkit
Tutorial: Database Communication in LabVIEW
Example:DSN
ThisExamplespecifiesaDSNcalledMSAccesstoopenaconnectiontothatspecificdatabase.
Example:DSNfromFile
YoucanuseapathtospecifyafileDSN.ThisexamplespecifiesapathtoafileDSNcalled“access.dsn”toopenaconnectiontothedatabase.
Example:DSNwithUserIdandPassword
MostDatabasesystems(DBMS–DatabaseManagementSystems)alsorequireaUserIdandaPassword.
9.1.2 UDL
WhereasyoumustcreateaDSNtoconnecttoadatabaseusingODBC,youuseUDL(UniversalDataLink)toconnecttodatabasesthatuseADOandOLEDB.
AUDLissimilartoaDSNinthatitdescribesmorethanjustthedatasource.AUDLspecifieswhatOLEDBproviderisused,serverinformation,theuserIDandpassword,thedefaultdatabase,andotherrelatedinformation.
InordertocreateanewUDLfile,createanemptytextfileandchangethefileextensionofthisdocumentfrom.txtto.udl.Youthencandouble-clicktheUDLfiletodisplaytheDataLinkPropertiesdialogbox.
42 LabVIEWDatabaseConnectivityToolkit
Tutorial: Database Communication in LabVIEW
Example:UDL
ConnecttoaDatabaseusingUDL:
9.1.3 ConnectionString
RatherthanincludinganexistingUDLinanapplication,youalsocanuseanODBCconnectionstringwiththeMicrosoftActiveXDataObject(ADO)standard.
Aconnectionstringiswrittenlikethis:
PROVIDER=SQLOLEDB;DATA SOURCE=server_name;UID=user_name;PWD=password;DATABASE=database_name;
Youcouldusemoreparameters,buttheparametersusedabovearethemostcommonones.
9.2 ReadingDatafromtheDatabase
43 LabVIEWDatabaseConnectivityToolkit
Tutorial: Database Communication in LabVIEW
Readingdatafromadatabasetableissimilartowritingdatatothedatabase.Youopenaconnectiontothedatabase,selectthedatafromatable,andthenclosetheconnection.
The“DBToolsSelectData.vi"isusedtoreaddatafromtheDatabase:
Example:SelectDatafromMSAccess
ThefollowingexamplegetsdatafromtheCUSTOMERtableinMSAccess.
TheFrontPanellookslikethis:
NoticeinFigures5-4and5-5thatthedatabasedataisreturnedasatwo-dimensionalarrayofvariants.Asthenameimplies,theMicrosoftActiveXDataObject(ADO)standardisbased
44 LabVIEWDatabaseConnectivityToolkit
Tutorial: Database Communication in LabVIEW
onActiveX,whichdefinesvariantsasitsdatatypes.VariantsworkwellinlanguagessuchasVisualBasicthatarenotstronglytyped.BecauseLabVIEWisstronglytyped,youmustusetheDatabaseVariantToDatafunctiontoconvertthevariantdatatoaLabVIEWdatatypebeforeyoucandisplaythedatainstandardindicatorssuchasgraphs,charts,andLEDs.
Example:SelectDatafromMSAccess
ThefollowingexamplegetsdatafromtheCUSTOMERtableinMSAccessandconvertsthedatatotext.
TheFrontPanellookslikethis:
Youmayreadfrommorethanonetableifyouuseacomma-delimitedstringtospecifymultipletablenames:
45 LabVIEWDatabaseConnectivityToolkit
Tutorial: Database Communication in LabVIEW
Youmayselectwhichcolumnsyouwanttoreadbyusingthe“Columns”input:
Youmayalsorestrictwhichdatatoreceiveusingthe“optionalClause”input:
Example:ReadData
UsingsomeVIsfromthe“Advanced”palette,createthefollowingexample:
46 LabVIEWDatabaseConnectivityToolkit
Tutorial: Database Communication in LabVIEW
9.3 WritingDatatotheDatabaseWritingdatatoadatabasewiththeLabVIEWDatabaseConnectivityToolkitissimilartoreadingdatatoafile.Youopenaconnection,insertthedata,andclosetheconnectionwhenyouarefinished.
The“DBToolsInsertData.vi"isusedtowritedatatotheDatabase:
Example:WriteData
Createthefollowingblockdiagram:
47 LabVIEWDatabaseConnectivityToolkit
Tutorial: Database Communication in LabVIEW
FrontPanel:
Example:WriteData
CreatethefollowingblockdiagramusingsomeVIsfromthe“Advanced”palette.
48 LabVIEWDatabaseConnectivityToolkit
Tutorial: Database Communication in LabVIEW
9.4 CreatingandDroppingTablesYoumayusestandardSQLsyntaxinordertocreate:
CREATE TABLE <TableName> (…)
Oryoumayusethe“DBToolsCreateTable.vi”inordertocreateatable.
YoumayusestandardSQLsyntaxinordertodroptables(deletetables):
DROP TABLE <TableName>
Oryoumayusethe“DBToolsDropTable.vi”inordertodrop/deleteatable.
49 LabVIEWDatabaseConnectivityToolkit
Tutorial: Database Communication in LabVIEW
9.5 UsingtheDatabaseConnectivityToolkitUtilityVIs
Inthe“Utility”palettethereareseveralusefulVIsforgettingmoreinformationabouttables,savingtotextfiles,etc.
HereisashortdescriptionoftheVIslocatedinthe“Utility”palette:
ThisVIliststhetablesinthedatabaseidentifiedbyconnectionreference.
ThisVIliststhecolumnspresentintable.Thecolumninformationincludesthename,thedatatype,andthedefinedsizeofthecolumn.
ThisVIsetspropertiesontheobjectasdeterminedbytheinputs.
ThisVIgetspropertiesoftheobjectasdeterminedbytheinputs.
ThisVIReturnsastringcontainingtheformatteddateandtime,andidentifiesthestringasadate/timestringsootherVIscaninterpretit.
ThisVIbegins,commits,orrollsbackatransactionforanytypeofreference.
50 LabVIEWDatabaseConnectivityToolkit
Tutorial: Database Communication in LabVIEW
ThisVIsavestherecordsetidentifiedbytherecordsetreferencetoeitheranXMLorADTGfile.TheADTGfileformatisaproprietaryformatthatonlytheLabVIEWDatabaseConnectivityToolkitcaninterpret.TheADTGformatresultsinasmallerfilethantheXMLformat.
ThisVIloadsarecordsetfromafileandreturnsarecordsetreferencethatidentifiesthisrecordset.Youcanretrievedatafromthisrecordsetlikeanyotherrecordset,butsomepropertiesmightnotbeavailableonthisrecordset.
9.6 PerformingAdvancedDatabaseOperationsWhencreatingrealprogramsyouwillsoonneedsomeoftheVIsinthe“Advanced”palette.
HereisashortdescriptionofsomeoftheVIslocatedinthe“Advanced”palette:
ThisVIExecutesanSQLqueryandreturnsarecordsetreferencethatyoumusteventuallyfreewiththeDBToolsFreeObjectVI.
ThisVIretrievesthedataintherecordsetidentifiedbytherecordsetreferenceinput.YoucanconverteachelementinthearraytoitsnativeLabVIEWdatatypeusingthe“DatabaseVariantToDatafunction”.
51 LabVIEWDatabaseConnectivityToolkit
Tutorial: Database Communication in LabVIEW
ThisVIfreesanobjectbydestroyingitsassociatedreferenceandreturnsadifferentreferenceobject.
52
10 CreatingandUsingTables
TheSQLsyntaxforcreatingaTableisasfollows:
CREATE TABLE <TableName> ( <ColumnName> <datatype> … )
TheSQLsyntaxforinsertingDataintoaTableisasfollows:
INSERT INTO <TableName> (<Column1>, <Column2>, …) VALUES(<Data for Column1>, <Data for Column2>, …)
Example:InsertDataintoTables
Wewillinsertsomedataintoourtables:
53 CreatingandUsingTables
Tutorial: Database Communication in LabVIEW
ThefollowingSQLQueryinsertssomeexampledataintothesetables:
--CUSTOMER INSERT INTO [CUSTOMER] ([FirstName],[LastName],[Address],[Phone],[PostCode],[PostAddress]) VALUES ('Per', 'Nilsen', 'Vipeveien 12', '12345678', '1234', 'Porsgrunn') GO INSERT INTO [CUSTOMER] ([FirstName],[LastName],[Address],[Phone],[PostCode],[PostAddress]) VALUES ('Tor', 'Hansen', 'Vipeveien 15', '77775678', '4455', 'Bergen') GO INSERT INTO [CUSTOMER] ([FirstName],[LastName],[Address],[Phone],[PostCode],[PostAddress]) VALUES ('Arne', 'Nilsen', 'Vipeveien 17', '12345778', '4434', 'Porsgrunn') GO --PRODUCT INSERT INTO [PRODUCT] ([ProductName],[ProductDescription],[Price],[ProductCode]) VALUES ('Product A', 'This is product A', 1000, 'A-1234') GO INSERT INTO [PRODUCT] ([ProductName],[ProductDescription],[Price],[ProductCode]) VALUES ('Product B', 'This is product B', 1000, 'B-1234') GO INSERT INTO [PRODUCT] ([ProductName],[ProductDescription],[Price],[ProductCode]) VALUES ('Product C', 'This is product C', 1000, 'C-1234') GO --ORDER INSERT INTO [ORDER] ([OrderNumber],[OrderDescription],[CustomerId]) VALUES ('10001', 'This is Order 10001', 1) GO INSERT INTO [ORDER] ([OrderNumber],[OrderDescription],[CustomerId]) VALUES ('10002', 'This is Order 10002', 2) GO INSERT INTO [ORDER] ([OrderNumber],[OrderDescription],[CustomerId]) VALUES ('10003', 'This is Order 10003', 3) GO --ORDER_DETAIL INSERT INTO [ORDER_DETAIL] ([OrderId],[ProductId]) VALUES (1, 1) GO INSERT INTO [ORDER_DETAIL] ([OrderId],[ProductId]) VALUES (1, 2) GO INSERT INTO [ORDER_DETAIL] ([OrderId],[ProductId]) VALUES (1, 3) GO INSERT INTO [ORDER_DETAIL] ([OrderId],[ProductId]) VALUES (2, 1) GO INSERT INTO [ORDER_DETAIL] ([OrderId],[ProductId]) VALUES (2, 2) GO INSERT INTO [ORDER_DETAIL] ([OrderId],[ProductId]) VALUES (3, 3) GO INSERT INTO [ORDER_DETAIL] ([OrderId],[ProductId]) VALUES (3, 1) GO INSERT INTO [ORDER_DETAIL] ([OrderId],[ProductId]) VALUES (3, 2) GO INSERT INTO [ORDER_DETAIL] ([OrderId],[ProductId]) VALUES (3, 3)
54 CreatingandUsingTables
Tutorial: Database Communication in LabVIEW
GO
ExecutingthefollowingQueriesthengives:
select * from CUSTOMER
select * from PRODUCT
select * from [ORDER]
select * from ORDER_DETAIL
55 CreatingandUsingTables
Tutorial: Database Communication in LabVIEW
10.1 ExercisesRunthequeriesabovefromLabVIEW.
56
11 CreatingandUsingViews
Indatabasetheory,aviewconsistsofastoredqueryaccessibleasavirtualtablecomposedoftheresultsetofaquery.Unlikeordinarytablesinarelationaldatabase,aviewdoesnotformpartofthephysicalschema:itisadynamic,virtualtablecomputedorcollatedfromdatainthedatabase.Changingthedatainatablealtersthedatashowninsubsequentinvocationsoftheview.
Viewscanprovideadvantagesovertables:
• Viewscanrepresentasubsetofthedatacontainedinatable • Viewscanjoinandsimplifymultipletablesintoasinglevirtualtable • Viewscanactasaggregatedtables,wherethedatabaseengineaggregatesdata
(sum,averageetc)andpresentsthecalculatedresultsaspartofthedata • Viewscanhidethecomplexityofdata;forexampleaviewcouldappearasSales2000
orSales2001,transparentlypartitioningtheactualunderlyingtable • Viewstakeverylittlespacetostore;thedatabasecontainsonlythedefinitionofa
view,notacopyofallthedataitpresents • DependingontheSQLengineused,viewscanprovideextrasecurity • Viewscanlimitthedegreeofexposureofatableortablestotheouterworld
Justasfunctions(inprogramming)canprovideabstraction,sodatabaseuserscancreateabstractionbyusingviews.Inanotherparallelwithfunctions,databaseuserscanmanipulatenestedviews,thusoneviewcanaggregatedatafromotherviews.
Syntax:
CREATE VIEW <ViewName> AS …
CreateaVIEW:
Step1:CreateanewView
57 CreatingandUsingTables
Tutorial: Database Communication in LabVIEW
Step2:Addyourtables
Step3:Addyourcolumns
58 CreatingandUsingTables
Tutorial: Database Communication in LabVIEW
Step4:Saveit
UsingtheVIEWinaQuery:
59 CreatingandUsingTables
Tutorial: Database Communication in LabVIEW
11.1 ExercisesCreateasimpleviewbasedontheexampletablesandruntheviewfromLabVIEW.
60
12 CreatingandusingStoredProcedures
Astoredprocedureisasubroutineavailabletoapplicationsaccessingarelationaldatabasesystem.Typicalusesforstoredproceduresincludedatavalidation(integratedintothedatabase)oraccesscontrolmechanisms.Furthermore,storedproceduresareusedtoconsolidateandcentralizelogicthatwasoriginallyimplementedinapplications.LargeorcomplexprocessingthatmightrequiretheexecutionofseveralSQLstatementsismovedintostoredprocedures,andallapplicationscalltheproceduresonly.
AstoredprocedureisaprecompiledcollectionofSQLstatementsandoptionalcontrol-of-flowstatements,similartoamacro.Eachdatabaseanddataprovidersupportsstoredproceduresdifferently.Storedproceduresofferthefollowingbenefitstoyourdatabaseapplications:
Performance—StoredProceduresareusuallymoreefficientandfasterthanregularSQLqueriesbecauseSQLstatementsareparsedforsyntacticalaccuracyandprecompiledbytheDBMSwhenthestoredprocedureiscreated.Also,combiningalargenumberofSQLstatementswithconditionallogicandparametersintoastoredprocedureallowstheprocedurestoperformqueries,makedecisions,andreturnresultswithoutextratripstothedatabaseserver.
Maintainability—StoredProceduresisolatethelower-leveldatabasestructurefromtheapplication.Aslongasthetablenames,columnnames,parameternames,andtypesdonotchangefromwhatisstatedinthestoredprocedure,youdonotneedtomodifytheprocedurewhenchangesaremadetothedatabaseschema.StoredproceduresarealsoawaytosupportmodularSQLprogrammingbecauseafteryoucreateaprocedure,youandotheruserscanreusethatprocedurewithoutknowingthedetailsofthetablesinvolved.
Security—Whencreatingtablesinadatabase,theDatabaseAdministratorcansetEXECUTEpermissionsonstoredprocedureswithoutgrantingSELECT,INSERT,UPDATE,andDELETEpermissionstousers.Therefore,thedatainthesetablesisprotectedfromuserswhoarenotusingthestoredprocedures.
Storedproceduresaresimilartouser-definedfunctions.ThemajordifferenceisthatfunctionscanbeusedlikeanyotherexpressionwithinSQLstatements,whereasstoredproceduresmustbeinvokedusingtheCALLstatement.
61 CreatingandusingStoredProcedures
Tutorial: Database Communication in LabVIEW
ThesyntaxforcreatingaStoredProcedureisasfollows:
CREATE PROCEDURE <ProcedureName> @<Parameter1> <datatype> …
Example:CreateaStoredProcedure
ThisProceduregetsCustomerDatabasedonaspecificOrderNumber.
IF EXISTS (SELECT name FROM sysobjects WHERE name = 'sp_CustomerOrders' AND type = 'P') DROP PROCEDURE sp_CustomerOrders GO CREATE PROCEDURE sp_CustomerOrders @OrderNumber varchar(50) AS /*------------------------------------------------------------------------- Last Updated Date: 2009.11.03 Last Updated By: [email protected] Description: Get Customer Information from a specific Order Number -------------------------------------------------------------------------*/ SET NOCOUNT ON declare @CustomerId int select @CustomerId = CustomerId from [ORDER] where OrderNumber = @OrderNumber select CustomerId, FirstName, LastName, [Address], Phone from CUSTOMER where CustomerId=@CustomerId SET NOCOUNT OFF GO
Example:UsingaStoredProcedure
UsingtheStoredprocedurelikethis
exec sp_CustomerOrders '10002'
givesthefollowingresult:
62 CreatingandusingStoredProcedures
Tutorial: Database Communication in LabVIEW
12.1 ExercisesRuntheStoredProcedurecreatedabovefromLabVIEW.
63
13 CreatingandUsingTriggers
Adatabasetriggerisproceduralcodethatisautomaticallyexecutedinresponsetocertaineventsonaparticulartableorviewinadatabase.Thetriggerismostlyusedforkeepingtheintegrityoftheinformationonthedatabase.Forexample,whenanewrecord(representinganewworker)addedtotheemployeestable,newrecordsshouldbecreatedalsointhetablesofthetaxes,vacations,andsalaries.
Triggersarecommonlyusedto:
• preventchanges(e.g.preventaninvoicefrombeingchangedafterit'sbeenmailedout)
• logchanges(e.g.keepacopyoftheolddata) • auditchanges(e.g.keepalogoftheusersandrolesinvolvedinchanges) • enhancechanges(e.g.ensurethateverychangetoarecordistime-stampedbythe
server'sclock,nottheclient's) • enforcebusinessrules(e.g.requirethateveryinvoicehaveatleastonelineitem) • executebusinessrules(e.g.notifyamanagereverytimeanemployee'sbankaccount
numberchanges) • replicatedata(e.g.storearecordofeverychange,tobeshippedtoanotherdatabase
later) • enhanceperformance(e.g.updatetheaccountbalanceaftereverydetailtransaction,
forfasterqueries)
Themajorfeaturesofdatabasetriggers,andtheireffects,are:
• donotacceptparametersorarguments(butmaystoreaffected-dataintemporarytables)
• cannotperformcommitorrollbackoperationsbecausetheyarepartofthetriggeringSQLstatement
• cancancelarequestedoperation • cancausemutatingtableerrors,iftheyarepoorlywritten.
64 CreatingandusingStoredProcedures
Tutorial: Database Communication in LabVIEW
MicrosoftSQLServersupportstriggerseitherafterorinsteadofaninsert,update,ordeleteoperation.
Thesyntaxisasfollows:
CREATE TRIGGER <TriggerName> on <TableName> FOR INSERT, UPDATE, DELETE AS … Create your Code here GO
• Replace<TriggerName>withtheNameofyourTrigger• Replace<TableName>withtheNameofyourTable
DefinewhentheTriggershouldbeexecute
• IftheTriggershouldbeexecutedonlywhenyouinsertdataintothetable:FOR INSERT
• IftheTriggershouldbeexecutedonlywhenyouupdatedataintothetable:FOR UPDATE
• IftheTriggershouldbeexecutedonlywhenyoudeletedataintothetable:FOR DELETE
• IftheTriggershouldbeexecutedwhenyouinsertandupdatedataintothetable:FOR INSERT, UPDATE
• Etc.
Example:Trigger
TheExampleabovechangethe“below”intheTable“SCHOOL”from‘TUC’to‘TelemarkUniversityCollege’
CREATE TRIGGER CheckSchoolData on SCHOOL FOR INSERT, UPDATE AS DECLARE @SchoolName varchar(50) select @SchoolName=SchoolName from INSERTED If @SchoolName='TUC' update SCHOOL set SchoolName='Telemark University College' where SchoolName=@SchoolName GO
65 CreatingandusingStoredProcedures
Tutorial: Database Communication in LabVIEW
Note!Notetheuseofatemporarytablecalled“INSERTED”.ThistemporarytablecontainsthelastinsertedrecordintotheSCHOOLtable
Note!InSQLyoudefineavariablelikethis
DECLARE @myVariable <datatype>
Example:
DECLARE @SchoolName varchar(10)
Note!Youhavetousethesymbol“@”beforethenameofthevariable!!!
BelowweseehowwecreateaTriggerfromthe“SQLServerManagementStudio”:
CheckiftheTriggerisworkingasexpected:
Procedure:
Step1:Checkthedatainyourtablebeforeyoudoanything,e.g.:
select * from SCHOOL
66 CreatingandusingStoredProcedures
Tutorial: Database Communication in LabVIEW
Step2:Insertsometestdataintoyourtable,e.g.:
insert into SCHOOL (SchoolId, SchoolName) values (5, 'TUC')
Step3:CheckthedatahasbeenupdatedaccordingtoyourcodeintheTrigger:
select * from SCHOOL
→AsyouseethedatayouinsertedintothetablehasbeenautomaticallybeenchangedbytheTrigger
13.1 ExercisesCreateaTriggerthatadds“+47”toallPhonenumbersintheCUSTOMERtable.
TestandseeiftheTriggerworksproperlybyinsertingandupdatingsomedataintheCUSTOMERtable.
67
14 CreatingandusingFunctions
InSQLdatabases,auser-definedfunctionprovidesamechanismforextendingthefunctionalityofthedatabaseserverbyaddingafunctionthatcanbeevaluatedinSQLstatements.TheSQLstandarddistinguishesbetweenscalarandtablefunctions.Ascalarfunctionreturnsonlyasinglevalue(orNULL),whereasatablefunctionreturnsa(relational)tablecomprisingzeroormorerows,eachrowwithoneormorecolumns.
StoredProceduresvs.Functions:
• Onlyfunctionscanreturnavalue(usingtheRETURNkeyword). • StoredprocedurescanuseRETURNkeywordbutwithoutanyvaluebeingpassed[1] • FunctionscouldbeusedinSELECTstatements,providedtheydon’tdoanydata
manipulationandalsoshouldnothaveanyOUTorINOUTparameters. • Functionsmustreturnavalue,butforstoredproceduresthisisnotcompulsory. • AfunctioncanhaveonlyINparameters,whilestoredproceduresmayhaveOUTorIN
OUTparameters. • Afunctionisasubprogramwrittentoperformcertaincomputationsandreturna
singlevalue. • Astoredprocedureisasubprogramwrittentoperformasetofactions,andcan
returnmultiplevaluesusingtheOUTparameterorreturnnovalueatall.
User-definedfunctionsinSQLaredeclaredusingtheCREATEFUNCTIONstatement.
14.1 ExercisesCreateasimplefunctionthatfindsnumberoforderforaspecificcustomeranduseitinthefollowingquery:
“Select FirstName, LastName, fn_NumberOfOrders(CustomerId) from CUSTOMER”
68
15 SQLToolkitIhavemadeasimpleandeasyto-useSQLToolkit.TheSQLToolkitisavailablefordownloadfrommyBlog:http://home.hit.no/~hansha/
15.1 InstallationTheinstallationprocedureisasfollows:
1. DownloadthezipfileSQLToolkit.zipfrommyBlog2. Unzipthefile3. Copy"SQLToolkit.mnu"to...\LabVIEW2009\menus\Categories\4. Copy"SQLToolkit.llb"to...\LabVIEW2009\vi.lib\5. TheSQLToolkitisreadytouseandintheFunctionspaletteinLabVIEWanewpalette
named"SQL"willappear.
TheSQLToolkitpaletteinavailableinLabVIEW:
TheSQLToolkitcontainsthefollowingVIs:
“SQLOpen.vi”-ThisVIopenaconnectiontothedatabasespecifiedintheConnectionstring.Theconnectionstringmaybeasfollows:
“PROVIDER=SQLOLEDB; DATA SOURCE=xxx;UID=xxx;PWD=xxx;DATABASE=xxx”
Youneedtoreplacethe“xxx”withtheparametersfromyourdatabase.
69 SQLToolkit
Tutorial: Database Communication in LabVIEW
“SQLSelect.vi”-ThisVIgetdatafromthedatabasespecifiedintheSQLQuery.Theoutputisa2Dstringarraywithdata.
“SQLExecute.vi”-ThisVIexecutesaQuerywithnoreturnData,e.g.,anINSERTstatement
“SQLClose.vi”-ThisVIClosetheconnectiontothedatabaseopenedby"SQLOpen.vi"
Twoexamplesarealsoincluded:
“SQL–Example1.vi”–Thisexampleselectsdatafromatable.Theexampleuses“SQLSelect.vi”inordertogetdatafromthedatabase.
Frontpanel:
BlockDiagram:
70 SQLToolkit
Tutorial: Database Communication in LabVIEW
“SQL–Example2.vi”–Thisexampleinsertsdataintoatable.Theexampleuses“SQLExecute.vi”inordertoinsertdataintothedatabase.Nodataisreturned.
Frontpanel:
BlockDiagram:
Example:GetDataintoLabVIEWusingSQLToolkit
DownloadtheSQLtoolkitfromtheHomepageoftheDatabaseLabandfollowtheinstructionsintheReadMefile.
OntheFunctionspaletteonyourBlockDiagramthefollowingpaletteshouldappear:
71 SQLToolkit
Tutorial: Database Communication in LabVIEW
HereisasimpleexampleofhowyougetdatafromthedatabaseintoLabVIEW:
Theprocedureisasfollows:
Step1:
Step2:
72 SQLToolkit
Tutorial: Database Communication in LabVIEW
Step3and4:
Step5:
73 SQLToolkit
Tutorial: Database Communication in LabVIEW
Step6:
Step7:
74 SQLToolkit
Tutorial: Database Communication in LabVIEW
Step8:
Hans-PetterHalvorsen,M.Sc.
E-mail:[email protected]
Blog:http://home.hit.no/~hansha/
UniversityCollegeofSoutheastNorway
www.usn.no