Download Database Communication in LabVIEW

Document related concepts

Serializability wikipedia , lookup

DBase wikipedia , lookup

IMDb wikipedia , lookup

Btrieve wikipedia , lookup

Oracle Database wikipedia , lookup

Microsoft Access wikipedia , lookup

Entity–attribute–value model wikipedia , lookup

Extensible Storage Engine wikipedia , lookup

Concurrency control wikipedia , lookup

Ingres (database) wikipedia , lookup

Functional Database Model wikipedia , lookup

SQL wikipedia , lookup

Microsoft SQL Server wikipedia , lookup

Database wikipedia , lookup

Microsoft Jet Database Engine wikipedia , lookup

PL/SQL wikipedia , lookup

Open Database Connectivity wikipedia , lookup

ContactPoint wikipedia , lookup

Clusterpoint wikipedia , lookup

Relational model wikipedia , lookup

Database model wikipedia , lookup

Transcript
UniversityCollegeofSoutheastNorway
DatabaseCommunication inLabVIEW
Hans-PetterHalvorsen,2016.10.31
http://home.hit.no/~hansha
Preface
Thisdocumentexplainsthebasicconceptsofadatabasesystemandhowtocommunicate
withadatabasefromLabVIEW.
YoushouldhavesomebasicknowledgeaboutLabVIEW,e.g.,the“AnIntroductionto
LabVIEW”training.Thisdocumentisavailablefordownloadat
http://home.hit.no/~hansha/.
InadditiontoLabVIEWProfessionalDevelopmentSystem,youneedtoinstallthe“LabVIEW
DatabaseConnectivityToolkit”.
FormoreinformationaboutLabVIEWandDatabases,visitmyBlog:
http://home.hit.no/~hansha/
Sometextinthisdocumentisbasedontextfromwww.wikipedia.organd“LabVIEW
DatabaseConnectivityToolkitUserManual”.
2
TableofContents
Preface......................................................................................................................................2
TableofContents.....................................................................................................................iii
1
2
3
IntroductiontoLabVIEW...................................................................................................1
1.1
Dataflowprogramming...............................................................................................1
1.2
Graphicalprogramming..............................................................................................1
1.3
Benefits.......................................................................................................................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
RelationalDatabases.........................................................................................................7
3.1
Tables..........................................................................................................................7
3.2
UniqueKeysandPrimaryKey.....................................................................................7
3.3
ForeignKey.................................................................................................................9
3.4
Views........................................................................................................................10
3.5
Functions..................................................................................................................10
iii
iv
4
5
6
7
TableofContents
3.6
Storedprocedures....................................................................................................11
3.7
Triggers.....................................................................................................................11
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
DatabaseModelling........................................................................................................17
5.1
ERDiagram...............................................................................................................17
5.2
MicrosoftVisio..........................................................................................................18
5.3
EXERCISES.....................................................................Error!Bookmarknotdefined.
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
MicrosoftOfficeAccess...................................................................................................28
Tutorial: Database Communication in LabVIEW
v
8
9
TableofContents
7.1
Introduction..............................................................................................................28
7.2
ExampleDatabase....................................................................................................28
7.3
Exercises...................................................................................................................30
ODBC...............................................................................................................................32
8.1
WhatisODBC?..........................................................................................................32
8.2
CreateanODBCConnectionin“ODBCDataSourceAdministrator”........................32
8.3
GetdataintoExcelusingyourODBCConnection.....................................................34
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
Tutorial: Database Communication in LabVIEW
vi
TableofContents
14.1 Exercises...................................................................................................................67
15 SQLToolkit......................................................................................................................68
15.1 Installation................................................................................................................68
Tutorial: Database Communication in LabVIEW
1 IntroductiontoLabVIEW
LabVIEW(shortforLaboratoryVirtualInstrumentationEngineeringWorkbench)isa
platformanddevelopmentenvironmentforavisualprogramminglanguagefromNational
Instruments.Thegraphicallanguageisnamed"G".OriginallyreleasedfortheApple
Macintoshin1986,LabVIEWiscommonlyusedfordataacquisition,instrumentcontrol,and
industrialautomationonavarietyofplatformsincludingMicrosoftWindows,variousflavors
ofUNIX,Linux,andMacOSX.ThelatestversionofLabVIEWisversionLabVIEW2009,
releasedinAugust2009.VisitNationalInstrumentsatwww.ni.com.
Thecodefileshavetheextension“.vi”,whichisaabbreviationfor“VirtualInstrument”.
LabVIEWofferslotsofadditionalAdd-OnsandToolkits.
1.1 Dataflowprogramming
TheprogramminglanguageusedinLabVIEW,alsoreferredtoasG,isadataflow
programminglanguage.Executionisdeterminedbythestructureofagraphicalblock
diagram(theLV-sourcecode)onwhichtheprogrammerconnectsdifferentfunction-nodes
bydrawingwires.Thesewirespropagatevariablesandanynodecanexecuteassoonasall
itsinputdatabecomeavailable.Sincethismightbethecaseformultiplenodes
simultaneously,Gisinherentlycapableofparallelexecution.Multi-processingandmultithreadinghardwareisautomaticallyexploitedbythebuilt-inscheduler,whichmultiplexes
multipleOSthreadsoverthenodesreadyforexecution.
1.2 Graphicalprogramming
LabVIEWtiesthecreationofuserinterfaces(calledfrontpanels)intothedevelopmentcycle.
LabVIEWprograms/subroutinesarecalledvirtualinstruments(VIs).EachVIhasthree
components:ablockdiagram,afrontpanel,andaconnectorpanel.Thelastisusedto
representtheVIintheblockdiagramsofother,callingVIs.Controlsandindicatorsonthe
frontpanelallowanoperatortoinputdataintoorextractdatafromarunningvirtual
instrument.However,thefrontpanelcanalsoserveasaprogrammaticinterface.Thusa
virtualinstrumentcaneitherberunasaprogram,withthefrontpanelservingasauser
interface,or,whendroppedasanodeontotheblockdiagram,thefrontpaneldefinesthe
1
2
IntroductiontoLabVIEW
inputsandoutputsforthegivennodethroughtheconnectorpane.ThisimplieseachVIcan
beeasilytestedbeforebeingembeddedasasubroutineintoalargerprogram.
Thegraphicalapproachalsoallowsnon-programmerstobuildprogramssimplybydragging
anddroppingvirtualrepresentationsoflabequipmentwithwhichtheyarealreadyfamiliar.
TheLabVIEWprogrammingenvironment,withtheincludedexamplesandthe
documentation,makesitsimpletocreatesmallapplications.Thisisabenefitononeside,
butthereisalsoacertaindangerofunderestimatingtheexpertiseneededforgoodquality
"G"programming.Forcomplexalgorithmsorlarge-scalecode,itisimportantthatthe
programmerpossessanextensiveknowledgeofthespecialLabVIEWsyntaxandthe
topologyofitsmemorymanagement.ThemostadvancedLabVIEWdevelopmentsystems
offerthepossibilityofbuildingstand-aloneapplications.Furthermore,itispossibletocreate
distributedapplications,whichcommunicatebyaclient/serverscheme,andaretherefore
easiertoimplementduetotheinherentlyparallelnatureofG-code.
1.3 Benefits
OnebenefitofLabVIEWoverotherdevelopmentenvironmentsistheextensivesupportfor
accessinginstrumentationhardware.Driversandabstractionlayersformanydifferenttypes
ofinstrumentsandbusesareincludedorareavailableforinclusion.Thesepresent
themselvesasgraphicalnodes.Theabstractionlayersofferstandardsoftwareinterfacesto
communicatewithhardwaredevices.Theprovideddriverinterfacessaveprogram
developmenttime.ThesalespitchofNationalInstrumentsis,therefore,thatevenpeople
withlimitedcodingexperiencecanwriteprogramsanddeploytestsolutionsinareduced
timeframewhencomparedtomoreconventionalorcompetingsystems.Anewhardware
drivertopology(DAQmxBase),whichconsistsmainlyofG-codedcomponentswithonlya
fewregistercallsthroughNIMeasurementHardwareDDK(DriverDevelopmentKit)
functions,providesplatformindependenthardwareaccesstonumerousdataacquisition
andinstrumentationdevices.TheDAQmxBasedriverisavailableforLabVIEWonWindows,
MacOSXandLinuxplatforms.
Tutorial: Database Communication in LabVIEW
2 DatabaseSystems
Adatabaseisanintegratedcollectionoflogicallyrelatedrecordsorfilesconsolidatedintoa
commonpoolthatprovidesdataforoneormoremultipleuses.
Onewayofclassifyingdatabasesinvolvesthetypeofcontent,forexample:bibliographic,
full-text,numeric,andimage.Otherclassificationmethodsstartfromexaminingdatabase
modelsordatabasearchitectures.
Thedatainadatabaseisorganizedaccordingtoadatabasemodel.Therelationalmodelis
themostcommon.
ADatabaseManagementSystem(DBMS)consistsofsoftwarethatorganizesthestorageof
data.ADBMScontrolsthecreation,maintenance,anduseofthedatabasestorage
structuresoforganizationsandoftheirendusers.Itallowsorganizationstoplacecontrolof
organization-widedatabasedevelopmentinthehandsofDatabaseAdministrators(DBAs)
andotherspecialists.Inlargesystems,aDBMSallowsusersandothersoftwaretostoreand
retrievedatainastructuredway.
Databasemanagementsystemsareusuallycategorizedaccordingtothedatabasemodel
thattheysupport,suchasthenetwork,relationalorobjectmodel.Themodeltendsto
determinethequerylanguagesthatareavailabletoaccessthedatabase.Onecommonly
usedquerylanguagefortherelationaldatabaseisSQL,althoughSQLsyntaxandfunction
canvaryfromoneDBMStoanother.AgreatdealoftheinternalengineeringofaDBMSis
independentofthedatamodel,andisconcernedwithmanagingfactorssuchas
performance,concurrency,integrity,andrecoveryfromhardwarefailures.Intheseareas
therearelargedifferencesbetweenproducts.
2.1 RDBMSComponents
ARelationalDatabaseManagementSystem(DBMS)consistsofthefollowingcomponents:
•
•
Interfacedrivers-Auserorapplicationprograminitiateseitherschemamodification
orcontentmodification.ThesedriversarebuiltontopofSQL.Theyprovidemethods
topreparestatements,executestatements,fetchresults,etc.Animportantexample
istheODBCdriver. SQLengine-ThiscomponentinterpretsandexecutestheSQLquery.Itcomprises
threemajorcomponents(compiler,optimizer,andexecutionengine). 3
4
•
•
•
2 Transactionengine-Transactionsaresequencesofoperationsthatreadorwrite
databaseelements,whicharegroupedtogether. Relationalengine-RelationalobjectssuchasTable,Index,andReferentialintegrity
constraintsareimplementedinthiscomponent. Storageengine-Thiscomponentstoresandretrievesdatarecords.Italsoprovidesa
mechanismtostoremetadataandcontrolinformationsuchasundologs,redologs,
locktables,etc.
2.2 Datawarehouse
Adatawarehousestoresdatafromcurrentandpreviousyears—dataextractedfromthe
variousoperationaldatabasesofanorganization.Itbecomesthecentralsourceofdatathat
hasbeenscreened,edited,standardizedandintegratedsothatitcanbeusedbymanagers
andotherend-userprofessionalsthroughoutanorganization.
2.3 RelationalDatabase
Arelationaldatabasematchesdatausingcommoncharacteristicsfoundwithinthedataset.
Theresultinggroupsofdataareorganizedandaremucheasierforpeopletounderstand.
Forexample,adatasetcontainingallthereal-estatetransactionsinatowncanbegrouped
bytheyearthetransactionoccurred;oritcanbegroupedbythesalepriceofthe
transaction;oritcanbegroupedbythebuyer'slastname;andsoon.
Suchagroupingusestherelationalmodel(atechnicaltermforthisisschema).Hence,such
adatabaseiscalleda"relationaldatabase."
Thesoftwareusedtodothisgroupingiscalledarelationaldatabasemanagementsystem.
Theterm"relationaldatabase"oftenreferstothistypeofsoftware.
Relationaldatabasesarecurrentlythepredominantchoiceinstoringfinancialrecords,
manufacturingandlogisticalinformation,personneldataandmuchmore.
Strictly,arelationaldatabaseisacollectionofrelations(frequentlycalledtables).
2.4 Real-timedatabases
Areal-timedatabaseisaprocessingsystemdesignedtohandleworkloadswhosestatemay
changeconstantly.Thisdiffersfromtraditionaldatabasescontainingpersistentdata,mostly
unaffectedbytime.Forexample,astockmarketchangesrapidlyanddynamically.Real-time
Tutorial: Database Communication in LabVIEW
5
2 processingmeansthatatransactionisprocessedfastenoughfortheresulttocomeback
andbeactedonrightaway.Real-timedatabasesareusefulforaccounting,banking,law,
medicalrecords,multi-media,processcontrol,reservationsystems,andscientificdata
analysis.Ascomputersincreaseinpowerandcanstoremoredata,real-timedatabases
becomeintegratedintosocietyandareemployedinmanyapplications
2.5 DatabaseManagementSystems
ThereareDatabaseManagementSystems(DBMS),suchas:
•
•
•
•
•
•
•
•
MicrosoftSQLServer
Oracle
Sybase
dBase
MicrosoftAccess
MySQLfromSunMicrosystems(Oracle)
DB2fromIBM
etc.
ThisdocumentwillfocusonMicrosoftAccessandMicrosoftSQLServer.
2.6 MDAC
TheMicrosoftDataAccessComponents(MDAC)istheframeworkthatmakesitpossibleto
connectandcommunicatewiththedatabase.MDACincludesthefollowingcomponents:
•
•
•
ODBC(OpenDatabaseConnectivity)
OLEDB
ADO(ActiveXDataObjects) MDACalsoinstallsseveraldataprovidersyoucanusetoopenaconnectiontoaspecificdata
source,suchasanMSAccessdatabase.
2.6.1
ODBC
OpenDatabaseConnectivity(ODBC)isanativeinterfacethatisaccessedthrougha
programminglanguagethatcanmakecallsintoanativelibrary.InMDACthisinterfaceis
definedasaDLL.Aseparatemoduleordriverisneededforeachdatabasethatmustbe
accessed. Tutorial: Database Communication in LabVIEW
6
2.6.2
2 OLEDB
OLEallowsMDACapplicationsaccesstodifferenttypesofdatastoresinauniformmanner.
Microsofthasusedthistechnologytoseparatetheapplicationfromthedatastorethatit
needstoaccess.Thiswasdonebecausedifferentapplicationsneedaccesstodifferenttypes
andsourcesofdata,anddonotnecessarilyneedtoknowhowtoaccesstechnology-specific
functionality.Thetechnologyisconceptuallydividedintoconsumersandproviders.The
consumersaretheapplicationsthatneedaccesstothedata,andtheprovideristhe
softwarecomponentthatexposesanOLEDBinterfacethroughtheuseoftheComponent
ObjectModel(orCOM).
2.6.3
ADO(ActiveXDataObjects) ActiveXDataObjects(ADO)isahighlevelprogramminginterfacetoOLEDB.Itusesa
hierarchicalobjectmodeltoallowapplicationstoprogrammaticallycreate,retrieve,update
anddeletedatafromsourcessupportedbyOLEDB.ADOconsistsofaseriesofhierarchical
COM-basedobjectsandcollections,anobjectthatactsasacontainerofmanyotherobjects.
AprogrammercandirectlyaccessADOobjectstomanipulatedata,orcansendanSQLquery
tothedatabaseviaseveralADOmechanisms.
Tutorial: Database Communication in LabVIEW
3 RelationalDatabases
Arelationaldatabasematchesdatausingcommoncharacteristicsfoundwithinthedataset.
Theresultinggroupsofdataareorganizedandaremucheasierforpeopletounderstand.
Forexample,adatasetcontainingallthereal-estatetransactionsinatowncanbegrouped
bytheyearthetransactionoccurred;oritcanbegroupedbythesalepriceofthe
transaction;oritcanbegroupedbythebuyer'slastname;andsoon.
Suchagroupingusestherelationalmodel(atechnicaltermforthisisschema).Hence,such
adatabaseiscalleda"relationaldatabase."
Thesoftwareusedtodothisgroupingiscalledarelationaldatabasemanagementsystem.
Theterm"relationaldatabase"oftenreferstothistypeofsoftware.
Relationaldatabasesarecurrentlythepredominantchoiceinstoringfinancialrecords,
manufacturingandlogisticalinformation,personneldataandmuchmore.
3.1 Tables
Thebasicunitsinadatabasearetablesandtherelationshipbetweenthem.Strictly,a
relationaldatabaseisacollectionofrelations(frequentlycalledtables).
3.2 UniqueKeysandPrimaryKey
7
8
RelationalDatabases Inrelationaldatabasedesign,auniquekeyorprimarykeyisacandidatekeytouniquely
identifyeachrowinatable.Auniquekeyorprimarykeycomprisesasinglecolumnorsetof
columns.Notwodistinctrowsinatablecanhavethesamevalue(orcombinationofvalues)
inthosecolumns.Dependingonitsdesign,atablemayhavearbitrarilymanyuniquekeys
butatmostoneprimarykey.
Auniquekeymustuniquelyidentifyallpossiblerowsthatexistinatableandnotonlythe
currentlyexistingrows.ExamplesofuniquekeysareSocialSecuritynumbersorISBNs. Aprimarykeyisaspecialcaseofuniquekeys.Themajordifferenceisthatforuniquekeys
theimplicitNOTNULLconstraintisnotautomaticallyenforced,whileforprimarykeysitis
enforced.Thus,thevaluesinuniquekeycolumnsmayormaynotbeNULL.Another
differenceisthatprimarykeysmustbedefinedusinganothersyntax.
Primarykeysaredefinedwiththefollowingsyntax:
CREATE TABLE table_name (
id_col INT,
col2
CHARACTER VARYING(20),
...
CONSTRAINT tab_pk PRIMARY KEY(id_col),
...
)
Iftheprimarykeyconsistsonlyofasinglecolumn,thecolumncanbemarkedassuchusing
thefollowingsyntax:
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,thecolumncanbemarkedassuch
usingthefollowingsyntax:
CREATE TABLE table_name (
Tutorial: Database Communication in LabVIEW
9
RelationalDatabases id_col INT PRIMARY KEY,
col2
CHARACTER VARYING(20),
...
key_col SMALLINT UNIQUE,
...
)
3.3 ForeignKey
Inthecontextofrelationaldatabases,aforeignkeyisareferentialconstraintbetweentwo
tables.Theforeignkeyidentifiesacolumnorasetofcolumnsinonetablethatreferstoa
columnorsetofcolumnsinanothertable.Thecolumnsinthereferencingtablemustbethe
primarykeyorothercandidatekeyinthereferencedtable.Thevaluesinonerowofthe
referencingcolumnsmustoccurinasinglerowinthereferencedtable.Thus,arowinthe
referencingtablecannotcontainvaluesthatdon'texistinthereferencedtable.Thisway
referencescanbemadetolinkinformationtogetheranditisanessentialpartofdatabase
normalization.Multiplerowsinthereferencingtablemayrefertothesamerowinthe
referencedtable.Mostofthetime,itreflectstheone(mastertable,orreferencedtable)to
many(childtable,orreferencingtable)relationship.
Thereferencingandreferencedtablemaybethesametable,i.e.theforeignkeyrefersback
tothesametable.Suchaforeignkeyisknownasself-referencingorrecursiveforeignkey.
Atablemayhavemultipleforeignkeys,andeachforeignkeycanhaveadifferentreferenced
table.Eachforeignkeyisenforcedindependentlybythedatabasesystem.Therefore,
cascadingrelationshipsbetweentablescanbeestablishedusingforeignkeys.
Improperforeignkey/primarykeyrelationshipsornotenforcingthoserelationshipsare
oftenthesourceofmanydatabaseanddatamodelingproblems.
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,thecolumncanbemarkedassuchusingthe
followingsyntax:
CREATE TABLE table_name (
id
INTEGER PRIMARY KEY,
col2 CHARACTER VARYING(20),
Tutorial: Database Communication in LabVIEW
10
RelationalDatabases col3 INTEGER REFERENCES other_table(column_name),
... )
3.4 Views
Indatabasetheory,aviewconsistsofastoredqueryaccessibleasavirtualtablecomposed
oftheresultsetofaquery.Unlikeordinarytablesinarelationaldatabase,aviewdoesnot
formpartofthephysicalschema:itisadynamic,virtualtablecomputedorcollatedfrom
datainthedatabase.Changingthedatainatablealtersthedatashowninsubsequent
invocationsoftheview.
Viewscanprovideadvantagesovertables:
•
•
•
•
•
•
Viewscanrepresentasubsetofthedatacontainedinatable Viewscanjoinandsimplifymultipletablesintoasinglevirtualtable Viewscanactasaggregatedtables,wherethedatabaseengineaggregatesdata
(sum,averageetc)andpresentsthecalculatedresultsaspartofthedata Viewscanhidethecomplexityofdata;forexampleaviewcouldappearasSales2000
orSales2001,transparentlypartitioningtheactualunderlyingtable Viewstakeverylittlespacetostore;thedatabasecontainsonlythedefinitionofa
view,notacopyofallthedataitpresents Viewscanlimitthedegreeofexposureofatableortablestotheouterworld
Syntax:
CREATE VIEW <ViewName>
AS
…
3.5 Functions
InSQLdatabases,auser-definedfunctionprovidesamechanismforextendingthe
functionalityofthedatabaseserverbyaddingafunctionthatcanbeevaluatedinSQL
statements.TheSQLstandarddistinguishesbetweenscalarandtablefunctions.Ascalar
functionreturnsonlyasinglevalue(orNULL),whereasatablefunctionreturnsa(relational)
tablecomprisingzeroormorerows,eachrowwithoneormorecolumns.
User-definedfunctionsinSQLaredeclaredusingtheCREATEFUNCTIONstatement.
Syntax:
CREATE FUNCTION <FunctionName>
(@Parameter1 <datatype>,
@ Parameter2 <datatype>,
Tutorial: Database Communication in LabVIEW
11
RelationalDatabases …)
RETURNS <datatype>
AS
…
3.6 Storedprocedures
Astoredprocedureisexecutablecodethatisassociatedwith,andgenerallystoredin,the
database.Storedproceduresusuallycollectandcustomizecommonoperations,like
insertingatupleintoarelation,gatheringstatisticalinformationaboutusagepatterns,or
encapsulatingcomplexbusinesslogicandcalculations.Frequentlytheyareusedasan
applicationprogramminginterface(API)forsecurityorsimplicity.
Storedproceduresarenotpartoftherelationaldatabasemodel,butallcommercial
implementationsincludethem.
Storedproceduresarecalledorusedwiththefollowingsyntax:
CALL procedure(…)
or
EXECUTE procedure(…)
Storedprocedurescanreturnresultsets,i.e.theresultsofaSELECTstatement.Suchresult
setscanbeprocessedusingcursorsbyotherstoredproceduresbyassociatingaresultset
locator,orbyapplications.Storedproceduresmayalsocontaindeclaredvariablesfor
processingdataandcursorsthatallowittoloopthroughmultiplerowsinatable.The
standardStructuredQueryLanguageprovidesIF,WHILE,LOOP,REPEAT,CASEstatements,
andmore.Storedprocedurescanreceivevariables,returnresultsormodifyvariablesand
returnthem,dependingonhowandwherethevariableisdeclared.
3.7 Triggers
Adatabasetriggerisproceduralcodethatisautomaticallyexecutedinresponsetocertain
eventsonaparticulartableorviewinadatabase.Thetriggerismostlyusedforkeepingthe
integrityoftheinformationonthedatabase.Forexample,whenanewrecord(representing
anewworker)addedtotheemployeestable,newrecordsshouldbecreatedalsointhe
tablesofthetaxes,vacations,andsalaries.
Thesyntaxisasfollows:
CREATE TRIGGER <TriggerName> ON <TableName>
Tutorial: Database Communication in LabVIEW
12
FOR INSERT, UPDATE, DELETE
AS
…
Tutorial: Database Communication in LabVIEW
RelationalDatabases 4 StructuredQueryLanguage
(SQL)
SQL(StructuredQueryLanguage)isadatabasecomputerlanguagedesignedformanaging
datainrelationaldatabasemanagementsystems(RDBMS).
4.1 Queries
ThemostcommonoperationinSQListhequery,whichisperformedwiththedeclarative
SELECTstatement.SELECTretrievesdatafromoneormoretables,orexpressions.Standard
SELECTstatementshavenopersistenteffectsonthedatabase.
Queriesallowtheusertodescribedesireddata,leavingthedatabasemanagementsystem
(DBMS)responsibleforplanning,optimizing,andperformingthephysicaloperations
necessarytoproducethatresultasitchooses.
Aqueryincludesalistofcolumnstobeincludedinthefinalresultimmediatelyfollowingthe
SELECTkeyword.Anasterisk("*")canalsobeusedtospecifythatthequeryshouldreturnall
columnsofthequeriedtables.SELECTisthemostcomplexstatementinSQL,withoptional
keywordsandclausesthatinclude:
•
•
•
•
TheFROMclausewhichindicatesthetable(s)fromwhichdataistoberetrieved.The
FROMclausecanincludeoptionalJOINsubclausestospecifytherulesforjoining
tables. TheWHEREclauseincludesacomparisonpredicate,whichrestrictstherows
returnedbythequery.TheWHEREclauseeliminatesallrowsfromtheresultsetfor
whichthecomparisonpredicatedoesnotevaluatetoTrue. TheGROUPBYclauseisusedtoprojectrowshavingcommonvaluesintoasmaller
setofrows.GROUPBYisoftenusedinconjunctionwithSQLaggregationfunctionsor
toeliminateduplicaterowsfromaresultset.TheWHEREclauseisappliedbeforethe
GROUPBYclause. TheHAVINGclauseincludesapredicateusedtofilterrowsresultingfromtheGROUP
BYclause.BecauseitactsontheresultsoftheGROUPBYclause,aggregation
functionscanbeusedintheHAVINGclausepredicate. 13
14
•
StructuredQueryLanguage(SQL) TheORDERBYclauseidentifieswhichcolumnsareusedtosorttheresultingdata,
andinwhichdirectiontheyshouldbesorted(optionsareascendingordescending).
WithoutanORDERBYclause,theorderofrowsreturnedbyanSQLqueryis
undefined. Example:
ThefollowingisanexampleofaSELECTquerythatreturnsalistofexpensivebooks.The
queryretrievesallrowsfromtheBooktableinwhichthepricecolumncontainsavalue
greaterthan100.00.Theresultissortedinascendingorderbytitle.Theasterisk(*)inthe
selectlistindicatesthatallcolumnsoftheBooktableshouldbeincludedintheresultset.
SELECT *
FROM Book
WHERE price > 100.00
ORDER BY title;
Theexamplebelowdemonstratesaqueryofmultipletables,grouping,andaggregation,by
returningalistofbooksandthenumberofauthorsassociatedwitheachbook.
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 Datamanipulation
TheDataManipulationLanguage(DML)isthesubsetofSQLusedtoadd,updateanddelete
data.
TheacronymCRUDreferstoallofthemajorfunctionsthatneedtobeimplementedina
relationaldatabaseapplicationtoconsideritcomplete.Eachletterintheacronymcanbe
mappedtoastandardSQLstatement:
Operation
SQL
Create
INSERT Read(Retrieve)
SELECT Tutorial: Database Communication in LabVIEW
15
StructuredQueryLanguage(SQL) 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 Datadefinition
TheDataDefinitionLanguage(DDL)managestableandindexstructure.Themostbasic
itemsofDDLaretheCREATE,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)
)
Tutorial: Database Communication in LabVIEW
16
StructuredQueryLanguage(SQL) 4.4 Datatypes
EachcolumninanSQLtabledeclaresthetype(s)thatcolumnmaycontain.ANSISQL
includesthefollowingdatatypes.
4.4.1
•
•
•
•
CHARACTER(n)orCHAR(n)—fixed-widthn-characterstring,paddedwithspacesas
needed CHARACTERVARYING(n)orVARCHAR(n)—variable-widthstringwithamaximum
sizeofncharacters NATIONALCHARACTER(n)orNCHAR(n)—fixedwidthstringsupportingan
internationalcharacterset NATIONALCHARACTERVARYING(n)orNVARCHAR(n)—variable-widthNCHARstring 4.4.2
•
•
Numbers
INTEGERandSMALLINT FLOAT,REALandDOUBLEPRECISION NUMERIC(precision,scale)orDECIMAL(precision,scale) 4.4.4
•
•
•
•
Bitstrings
BIT(n)—anarrayofnbits BITVARYING(n)—anarrayofuptonbits 4.4.3
•
•
•
Characterstrings
DateandTime
DATE TIME TIMESTAMP INTERVAL
Tutorial: Database Communication in LabVIEW
5 DatabaseModelling
5.1 ERDiagram
Insoftwareengineering,anEntity-RelationshipModel(ERM)isanabstractandconceptual
representationofdata.Entity-relationshipmodelingisadatabasemodelingmethod,usedto
produceatypeofconceptualschemaorsemanticdatamodelofasystem,oftenarelational
database,anditsrequirementsinatop-downfashion.
Diagramscreatedusingthisprocessarecalledentity-relationshipdiagrams,orERdiagrams
orERDsforshort.
[Wikipedia]
TherearemanyERdiagrammingtools.SomeoftheproprietaryERdiagrammingtoolsare
ERwin,EnterpriseArchitectandMicrosoftVisio. MicrosoftSQLServerhasalsoabuilt-intoolforcreatingDatabaseDiagrams.
17
18
DatabaseModelling 5.2 MicrosoftVisio
MicrosoftVisioisadiagrammingprogramforcreatingdifferentkindsofdiagrams.Visiohave
atemplateforcreatingDatabaseModelDiagrams.
IntheDatabasemenuVisioofferslotsoffunctionalityregardingyourdatabasemodel.
Tutorial: Database Communication in LabVIEW
19
DatabaseModelling “ReverseEngineering”istheoppositeprocedure,i.e.,extractionofadatabaseschemafrom
anexistingdatabaseintoadatabasemodelinMicrosoftVisio.
5.3 Exercises
Exercise:DatabaseDiagram
CreatethefollowingtablesinanERDiagramusingMSVisio.
•
•
•
CUSTOMER
o CustomerId(PK)
o FirstName
o LastName
o Address
o Phone
o PostCode
o PostAddress
PRODUCT
o ProductId(PK)
o ProductName
o ProductDescription
o Price
o ProductCode
ORDER
o OrderId(PK)
o OrderNumber
Tutorial: Database Communication in LabVIEW
20
•
DatabaseModelling o OrderDescription
o CustomerId(FK)
ORDER_DETAIL
o OrderDetailId(PK)
o OrderId(FK)
o ProductId(FK)
DatabaseDiagram:
Tutorial: Database Communication in LabVIEW
6 MicrosoftSQLServer
6.1 Introduction
MicrosoftSQLServerisarelationalmodeldatabaseserverproducedbyMicrosoft.Its
primaryquerylanguagesareT-SQLandANSISQL.
ThelatestversionisMicrosoftSQLServer2008.
MicrosoftSQLServerhomepage:www.microsoft.com/sqlserver
TheMicrosoftSQLServercomesindifferentversions,suchas:
•
•
•
•
•
SQLServerDeveloperEdition
SQLServerEnterpriseEdition
SQLServerWebEdition
SQLServerExpressEdition
Etc.
TheSQLServerExpressEditionisafreely-downloadableand-distributableversion.
6.2 Requirements
InordertoinstallSQLServer2008,youneed:
•
•
•
Microsoft.NETFramework3.5SP1
WindowsInstaller4.5
WindowsPowerShell1.0
Note:YoumusthaveadministrativerightsonthecomputertoinstallMicrosoftSQLServer
2008.
6.3 SQLServerExpress
TheSQLServerExpressEditionisafreely-downloadableand-distributableversion.
21
22
MicrosoftSQLServer However,theExpresseditionhasanumberoftechnicalrestrictionswhichmakeit
undesirableforlarge-scaledeployments,including:
•
•
•
Maximumdatabasesizeof4GBper.The4GBlimitappliesperdatabase(logfiles
excluded);butinsomescenariosuserscanaccessmoredatathroughtheuseof
multipleinterconnecteddatabases. SinglephysicalCPU,multiplecores 1GBofRAM(runsonanysizeRAMsystem,butusesonly1GB)
SQLServerExpressoffersaGUItoolsfordatabasemanagementinaseparatedownloadand
installationpackage,calledSQLServerManagementStudioExpress.
6.4 AdventureWorks
TheAdventureWorksisasampleDatabasewithlotsofexamples,etc.
YoushouldinstallthissampleDatabasebecausesomeoftheexamplesinthisdocumentwill
usetheAdventureWorksdatabase.
6.5 SQLServerManagementStudio
SQLServerManagementStudioisaGUItoolincludedwithSQLServerforconfiguring,
managing,andadministeringallcomponentswithinMicrosoftSQLServer.Thetoolincludes
bothscripteditorsandgraphicaltoolsthatworkwithobjectsandfeaturesoftheserver.As
mentionedearlier,versionofSQLServerManagementStudioisalsoavailableforSQLServer
ExpressEdition,forwhichitisknownasSQLServerManagementStudioExpress.
AcentralfeatureofSQLServerManagementStudioistheObjectExplorer,whichallowsthe
usertobrowse,select,andactuponanyoftheobjectswithintheserver.Itcanbeusedto
visuallyobserveandanalyzequeryplansandoptimizethedatabaseperformance,among
others.SQLServerManagementStudiocanalsobeusedtocreateanewdatabase,alterany
existingdatabaseschemabyaddingormodifyingtablesandindexes,oranalyze
performance.ItincludesthequerywindowswhichprovideaGUIbasedinterfacetowrite
andexecutequeries.
Tutorial: Database Communication in LabVIEW
23
MicrosoftSQLServer 6.6 CreateanewDatabase
ItisquitesimpletocreateanewdatabaseinMicrosoftSQLServer.Justright-clickonthe
“Databases”nodeandselect“NewDatabase…”
Tutorial: Database Communication in LabVIEW
24
MicrosoftSQLServer Therearelotsofsettingsyoumaysetregardingyourdatabase,buttheonlyinformationyou
mustfillinisthenameofyourdatabase:
6.7 Backup/Restore
Animportanttaskindatabasesystemsistotakebackupofthedatabasewithregular
intervals,e.g.,duringthenightwhenthesystemisnotinuse.
DatabasebackupandRestore:
Tutorial: Database Communication in LabVIEW
25
MicrosoftSQLServer 6.8 ExampleDatabase
Examplesandexercisesinthistrainingarebasedonsomebasictables.TheExample
DatabaseconsistsofthefollowingTables:
Tutorial: Database Communication in LabVIEW
26
•
•
•
•
MicrosoftSQLServer CUSTOMER
o CustomerId(PK)
o FirstName
o LastName
o Address
o Phone
o PostCode
o PostAddress
PRODUCT
o ProductId(PK)
o ProductName
o ProductDescription
o Price
o ProductCode
ORDER
o OrderId(PK)
o OrderNumber
o OrderDescription
o CustomerId(FK)
ORDER_DETAIL
o OrderDetailId(PK)
o OrderId(FK)
o ProductId(FK)
Tutorial: Database Communication in LabVIEW
27
MicrosoftSQLServer 6.9 Exercises
Exercise:NewDatabase
CreateanewDatabaseinMSSQLServercalledTEST_SQLSERVER.
Exercise:DatabaseDiagram
CreatethetablesintheExampleDatabaseusingtheDiagramDesignerToolinMicrosoftSQL
Server.
Exercise:DatabaseScript
CreatethetablesintheExampleDatabaseTablesusingSQLCode.SavetheTablesasaSQL
Scriptfile(.sql).UseTheQueryToolinMicrosoftSQLServer.
Exercise:ODBC
CreateanODBCconnectionfortheDatabase.
Tutorial: Database Communication in LabVIEW
7 MicrosoftOfficeAccess
7.1 Introduction
MicrosoftOfficeAccess,previouslyknownasMicrosoftAccess,isarelationaldatabase
managementsystemfromMicrosoftthatcombinestherelationalMicrosoftJetDatabase
Enginewithagraphicaluserinterfaceandsoftwaredevelopmenttools.Itisamemberofthe
MicrosoftOfficesuiteofapplicationsandisincludedintheProfessionalandhigherversions
forWindows.AccessstoresdatainitsownformatbasedontheAccessJetDatabaseEngine.
MicrosoftAccessisusedbyprogrammersandnon-programmerstocreatetheirownsimple
databasesolutions.
MicrosoftAccessisafileserver-baseddatabase.Unlikeclient-serverrelationaldatabase
managementsystems(RDBMS),e.g.,MicrosoftSQLServer,MicrosoftAccessdoesnot
implementdatabasetriggers,storedprocedures,ortransactionlogging.Alldatabasetables,
queries,forms,reports,macros,andmodulesarestoredintheAccessJetdatabaseasa
singlefile.ThismakesMicrosoftAccessusefulinsmallapplications,teaching,etc.becauseit
iseasytomovefromonecomputertoanother.
7.2 ExampleDatabase
IwillpresentanexampledatabaseinMicrosoftAccess2007whichwillbeusedinsomeof
theexamplesandexercisesinthisdocument.
Thedatabaseconsistsofthefollowingtables:
•
•
CUSTOMER
o CustomerId(PK)
o FirstName
o LastName
o Address
o Phone
o PostCode
o PostAddress
PRODUCT
28
29
•
•
MicrosoftOfficeAccess o ProductId(PK)
o ProductName
o ProductDescription
o Price
o ProductCode
ORDER
o OrderId(PK)
o OrderNumber
o OrderDescription
o CustomerId(FK)
ORDER_DETAIL
o OrderDetailId(PK)
o OrderId(FK)
o ProductId(FK)
ODBCConnection:
AdministrativeTools→DataSources(ODBC)
Tutorial: Database Communication in LabVIEW
30
MicrosoftOfficeAccess 7.3 Exercises
Exercise:Database
CreateanewDatabaseinMSAccesscalledTEST.
Exercise:DatabaseTables
Tutorial: Database Communication in LabVIEW
31
MicrosoftOfficeAccess CreatethetablesintheExampleDatabaseTablesusingtheDiagramDesignerToolin
MicrosoftSQLServer.
Exercise:ODBC
CreateanODBCconnectionfortheDatabase.
Tutorial: Database Communication in LabVIEW
8 ODBC
8.1 WhatisODBC?
Incomputing,OpenDatabaseConnectivity(ODBC)providesastandardsoftwareAPImethod
forusingdatabasemanagementsystems(DBMS).ThedesignersofODBCaimedtomakeit
independentofprogramminglanguages,databasesystems,andoperatingsystems.
8.2 CreateanODBCConnectionin“ODBCData
SourceAdministrator”
Followthesesteps:
AddanewDataSourceandselecttheSQLServerdriver:
TypeaNameforyourConnectionandyourSQLServerName.YoufindyourServername
asshownbelow:
32
33
ODBC SelectSQLServerauthenticationandtypeyoursapassword(SystemAdministrator). You
definedthepasswordforthesauserduringthesetupprocedureofSQLServer:
CompleteyourconfigurationandTestyourdatasourcetoseeifitsOK:
Tutorial: Database Communication in LabVIEW
34
ODBC Ifyougetthismessageyouhavesucceeded:
8.3 GetdataintoExcelusingyourODBC
Connection
ThepurposeistouseExcelasaclientandgetdataintoExcelfromyourSQLServer.
Step1:OpenExcelandgototheDatasection:
Tutorial: Database Communication in LabVIEW
35
ODBC Step2:SelectyourODBCconnection
Step3:SelectyourTable(s)
Tutorial: Database Communication in LabVIEW
36
ODBC Step4:InsertDataintoExcel
Theresultsshouldlooksomethinglikethis:
Tutorial: Database Communication in LabVIEW
37
ODBC Tutorial: Database Communication in LabVIEW
9 LabVIEWDatabase
ConnectivityToolkit
LabVIEWoffersanadditionalToolkitcalled“LabVIEWDatabaseConnectivityToolkit”.With
thistoolkityoucancommunicatewithdifferentdatabases,suchasSQLServer,Oracle,etc.
FunctionsPalette:Connectivity→Database
ThefollowinglistdescribesthemainfeaturesoftheDatabaseConnectivityToolkit:
•
•
•
•
•
•
•
WorkswithanyproviderthatadherestotheMicrosoftActiveXDataObject(ADO)
standard.
WorkswithanydatabasedriverthatcomplieswithODBCorOLEDB.
Maintainsahighlevelofportability.Inmanycases,youcanportanapplicationto
anotherdatabasebychangingtheconnectioninformationyoupasstotheDBTools
OpenConnectionVI.
ConvertsdatabasecolumnvaluesfromnativedatatypestostandardDatabase
ConnectivityToolkitdatatypes,furtherenhancingportability.
PermitstheuseofSQLstatementswithallsupporteddatabasesystems,evennonSQLsystems.
IncludesVIstoretrievethenameanddatatypeofacolumnreturnedbyaSELECT
statement.
Createstablesandselects,inserts,updates,anddeletesrecordswithoutusingSQL
statements.
38
39
LabVIEWDatabaseConnectivityToolkit Someofthetextinthischapterisbasedonthe“LabVIEWDatabaseConnectivityToolkit
UserManual”.
9.1 ConnecttotheDatabase
BeforeyoucanaccessdatainatableorexecuteSQLstatements,youmustestablisha
connectiontoadatabase.Youmayusedifferentmethodsinordertoconnecttothe
database:
•
•
•
ODBCDataSourceName(DSN)
UniversalDataLink(UDL)
ConnectionString
Thesedifferentmethodsareexplainedbelow.
Forallofthesemethods,youwillusethesameVI:
Connectingtoadatabaseiswheremosterrorsoccurbecauseeachdatabasemanagement
system(DBMS)usesdifferentparametersfortheconnectionanddifferentlevelsofsecurity.
Thedifferentstandardsalsousedifferentmethodsofconnectingtodatabases.Forexample,
ODBCusesDataSourceNames(DSN)fortheconnection,whereastheMicrosoftActiveX
DataObject(ADO)standardusesUniversalDataLinks(UDL)fortheconnection.The“DB
ToolsOpenConnection.vi”VIsupportsallthesemethodsforconnectingtoadatabase.
Whenyouarefinishedwithreadingfromthedatabaseandwritingtothedatabase,you
shouldalwaysclosetheConnection.Usethe“DBToolsCloseConnection.vi”.
Tutorial: Database Communication in LabVIEW
40
LabVIEWDatabaseConnectivityToolkit 9.1.1
DSN
ADSN(ODBCDataSourceName(DSN))isthenameofthedatasource,ordatabase,to
whichyouareconnecting.TheDSNalsocontainsinformationabouttheODBCdriverand
otherconnectionattributesincludingpaths,securityinformation,andread-onlystatusof
thedatabase.TwomaintypesofDSNsexist:machineDSNsandfileDSNs.MachineDSNsare
inthesystemregistryandapplytoallusersofthecomputersystemortoasingleuser.DSNs
thatapplytoallusersofacomputersystemaresystemDSNs.DSNsthatapplytosingleusers
areuserDSNs.AfileDSNisatextfilewitha.dsnextensionandisaccessibletoanyonewith
properpermissions.FileDSNsarenotrestrictedtoasingleuserorcomputersystem.Usethe
ODBCDataSourceAdministratortocreateandconfigureDSNs.
IntheControlPanel,AdministrativeTools,youfindtheODBCDataSourceAdministrator
tool.
Tutorial: Database Communication in LabVIEW
41
LabVIEWDatabaseConnectivityToolkit Example:DSN
ThisExamplespecifiesaDSNcalledMSAccesstoopenaconnectiontothatspecific
database.
Example:DSNfromFile
YoucanuseapathtospecifyafileDSN.ThisexamplespecifiesapathtoafileDSNcalled
“access.dsn”toopenaconnectiontothedatabase.
Example:DSNwithUserIdandPassword
MostDatabasesystems(DBMS–DatabaseManagementSystems)alsorequireaUserIdand
aPassword.
9.1.2
UDL
WhereasyoumustcreateaDSNtoconnecttoadatabaseusingODBC,youuseUDL
(UniversalDataLink)toconnecttodatabasesthatuseADOandOLEDB.
AUDLissimilartoaDSNinthatitdescribesmorethanjustthedatasource.AUDLspecifies
whatOLEDBproviderisused,serverinformation,theuserIDandpassword,thedefault
database,andotherrelatedinformation.
InordertocreateanewUDLfile,createanemptytextfileandchangethefileextensionof
thisdocumentfrom.txtto.udl.Youthencandouble-clicktheUDLfiletodisplaytheData
LinkPropertiesdialogbox.
Tutorial: Database Communication in LabVIEW
42
LabVIEWDatabaseConnectivityToolkit Example:UDL
ConnecttoaDatabaseusingUDL:
9.1.3
ConnectionString
RatherthanincludinganexistingUDLinanapplication,youalsocanuseanODBC
connectionstringwiththeMicrosoftActiveXDataObject(ADO)standard. Aconnectionstringiswrittenlikethis:
PROVIDER=SQLOLEDB;DATA
SOURCE=server_name;UID=user_name;PWD=password;DATABASE=database_name;
Youcouldusemoreparameters,buttheparametersusedabovearethemostcommon
ones.
9.2 ReadingDatafromtheDatabase
Tutorial: Database Communication in LabVIEW
43
LabVIEWDatabaseConnectivityToolkit Readingdatafromadatabasetableissimilartowritingdatatothedatabase.Youopena
connectiontothedatabase,selectthedatafromatable,andthenclosetheconnection.
The“DBToolsSelectData.vi"isusedtoreaddatafromtheDatabase:
Example:SelectDatafromMSAccess
ThefollowingexamplegetsdatafromtheCUSTOMERtableinMSAccess.
TheFrontPanellookslikethis:
NoticeinFigures5-4and5-5thatthedatabasedataisreturnedasatwo-dimensionalarray
ofvariants.Asthenameimplies,theMicrosoftActiveXDataObject(ADO)standardisbased
Tutorial: Database Communication in LabVIEW
44
LabVIEWDatabaseConnectivityToolkit onActiveX,whichdefinesvariantsasitsdatatypes.Variantsworkwellinlanguagessuchas
VisualBasicthatarenotstronglytyped.BecauseLabVIEWisstronglytyped,youmustuse
theDatabaseVariantToDatafunctiontoconvertthevariantdatatoaLabVIEWdatatype
beforeyoucandisplaythedatainstandardindicatorssuchasgraphs,charts,andLEDs.
Example:SelectDatafromMSAccess
ThefollowingexamplegetsdatafromtheCUSTOMERtableinMSAccessandconvertsthe
datatotext.
TheFrontPanellookslikethis:
Youmayreadfrommorethanonetableifyouuseacomma-delimitedstringtospecify
multipletablenames:
Tutorial: Database Communication in LabVIEW
45
LabVIEWDatabaseConnectivityToolkit Youmayselectwhichcolumnsyouwanttoreadbyusingthe“Columns”input:
Youmayalsorestrictwhichdatatoreceiveusingthe“optionalClause”input:
Example:ReadData
UsingsomeVIsfromthe“Advanced”palette,createthefollowingexample:
Tutorial: Database Communication in LabVIEW
46
LabVIEWDatabaseConnectivityToolkit 9.3 WritingDatatotheDatabase
WritingdatatoadatabasewiththeLabVIEWDatabaseConnectivityToolkitissimilarto
readingdatatoafile.Youopenaconnection,insertthedata,andclosetheconnectionwhen
youarefinished.
The“DBToolsInsertData.vi"isusedtowritedatatotheDatabase:
Example:WriteData
Createthefollowingblockdiagram:
Tutorial: Database Communication in LabVIEW
47
LabVIEWDatabaseConnectivityToolkit FrontPanel:
Example:WriteData
CreatethefollowingblockdiagramusingsomeVIsfromthe“Advanced”palette.
Tutorial: Database Communication in LabVIEW
48
LabVIEWDatabaseConnectivityToolkit 9.4 CreatingandDroppingTables
YoumayusestandardSQLsyntaxinordertocreate:
CREATE TABLE <TableName> (…)
Oryoumayusethe“DBToolsCreateTable.vi”inordertocreateatable.
YoumayusestandardSQLsyntaxinordertodroptables(deletetables):
DROP TABLE <TableName>
Oryoumayusethe“DBToolsDropTable.vi”inordertodrop/deleteatable.
Tutorial: Database Communication in LabVIEW
49
LabVIEWDatabaseConnectivityToolkit 9.5 UsingtheDatabaseConnectivityToolkit
UtilityVIs
Inthe“Utility”palettethereareseveralusefulVIsforgettingmoreinformationabout
tables,savingtotextfiles,etc.
HereisashortdescriptionoftheVIslocatedinthe“Utility”palette:
ThisVIliststhetablesinthedatabaseidentifiedbyconnectionreference.
ThisVIliststhecolumnspresentintable.Thecolumninformation
includesthename,thedatatype,andthedefinedsizeofthecolumn.
ThisVIsetspropertiesontheobjectasdeterminedbytheinputs.
ThisVIgetspropertiesoftheobjectasdeterminedbytheinputs. ThisVIReturnsastringcontainingtheformatteddateandtime,
andidentifiesthestringasadate/timestringsootherVIscaninterpretit.
ThisVIbegins,commits,orrollsbackatransactionforanytypeof
reference.
Tutorial: Database Communication in LabVIEW
50
LabVIEWDatabaseConnectivityToolkit ThisVIsavestherecordsetidentifiedbytherecordsetreference
toeitheranXMLorADTGfile.TheADTGfileformatisaproprietaryformatthatonlythe
LabVIEWDatabaseConnectivityToolkitcaninterpret.TheADTGformatresultsinasmaller
filethantheXMLformat.
ThisVIloadsarecordsetfromafileandreturnsarecordset
referencethatidentifiesthisrecordset.Youcanretrievedatafromthisrecordsetlikeany
otherrecordset,butsomepropertiesmightnotbeavailableonthisrecordset.
9.6 PerformingAdvancedDatabaseOperations
WhencreatingrealprogramsyouwillsoonneedsomeoftheVIsinthe“Advanced”palette.
HereisashortdescriptionofsomeoftheVIslocatedinthe“Advanced”palette:
ThisVIExecutesanSQLqueryandreturnsarecordsetreferencethat
youmusteventuallyfreewiththeDBToolsFreeObjectVI.
ThisVIretrievesthedataintherecordsetidentifiedbythe
recordsetreferenceinput.YoucanconverteachelementinthearraytoitsnativeLabVIEW
datatypeusingthe“DatabaseVariantToDatafunction”.
Tutorial: Database Communication in LabVIEW
51
LabVIEWDatabaseConnectivityToolkit ThisVIfreesanobjectbydestroyingitsassociatedreferenceandreturns
adifferentreferenceobject.
Tutorial: Database Communication in LabVIEW
10 CreatingandUsing
Tables
TheSQLsyntaxforcreatingaTableisasfollows:
CREATE TABLE <TableName>
(
<ColumnName> <datatype>
…
)
TheSQLsyntaxforinsertingDataintoaTableisasfollows:
INSERT INTO <TableName> (<Column1>, <Column2>, …)
VALUES(<Data for Column1>, <Data for Column2>, …)
Example:InsertDataintoTables
Wewillinsertsomedataintoourtables:
52
53
CreatingandUsingTables 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]
GO
INSERT INTO [ORDER_DETAIL]
GO
INSERT INTO [ORDER_DETAIL]
GO
INSERT INTO [ORDER_DETAIL]
GO
INSERT INTO [ORDER_DETAIL]
GO
INSERT INTO [ORDER_DETAIL]
GO
INSERT INTO [ORDER_DETAIL]
GO
INSERT INTO [ORDER_DETAIL]
GO
INSERT INTO [ORDER_DETAIL]
([OrderId],[ProductId]) VALUES (1, 1)
([OrderId],[ProductId]) VALUES (1, 2)
([OrderId],[ProductId]) VALUES (1, 3)
([OrderId],[ProductId]) VALUES (2, 1)
([OrderId],[ProductId]) VALUES (2, 2)
([OrderId],[ProductId]) VALUES (3, 3)
([OrderId],[ProductId]) VALUES (3, 1)
([OrderId],[ProductId]) VALUES (3, 2)
([OrderId],[ProductId]) VALUES (3, 3)
Tutorial: Database Communication in LabVIEW
54
CreatingandUsingTables GO
ExecutingthefollowingQueriesthengives:
select * from CUSTOMER
select * from PRODUCT
select * from [ORDER]
select * from ORDER_DETAIL
Tutorial: Database Communication in LabVIEW
55
CreatingandUsingTables 10.1
Exercises
RunthequeriesabovefromLabVIEW.
Tutorial: Database Communication in LabVIEW
11 CreatingandUsing
Views
Indatabasetheory,aviewconsistsofastoredqueryaccessibleasavirtualtablecomposed
oftheresultsetofaquery.Unlikeordinarytablesinarelationaldatabase,aviewdoesnot
formpartofthephysicalschema:itisadynamic,virtualtablecomputedorcollatedfrom
datainthedatabase.Changingthedatainatablealtersthedatashowninsubsequent
invocationsoftheview.
Viewscanprovideadvantagesovertables:
•
•
•
•
•
•
•
Viewscanrepresentasubsetofthedatacontainedinatable Viewscanjoinandsimplifymultipletablesintoasinglevirtualtable Viewscanactasaggregatedtables,wherethedatabaseengineaggregatesdata
(sum,averageetc)andpresentsthecalculatedresultsaspartofthedata Viewscanhidethecomplexityofdata;forexampleaviewcouldappearasSales2000
orSales2001,transparentlypartitioningtheactualunderlyingtable Viewstakeverylittlespacetostore;thedatabasecontainsonlythedefinitionofa
view,notacopyofallthedataitpresents DependingontheSQLengineused,viewscanprovideextrasecurity Viewscanlimitthedegreeofexposureofatableortablestotheouterworld Justasfunctions(inprogramming)canprovideabstraction,sodatabaseuserscancreate
abstractionbyusingviews.Inanotherparallelwithfunctions,databaseuserscanmanipulate
nestedviews,thusoneviewcanaggregatedatafromotherviews. Syntax:
CREATE VIEW <ViewName>
AS
…
CreateaVIEW:
Step1:CreateanewView
56
57
CreatingandUsingTables Step2:Addyourtables
Step3:Addyourcolumns
Tutorial: Database Communication in LabVIEW
58
CreatingandUsingTables Step4:Saveit
UsingtheVIEWinaQuery:
Tutorial: Database Communication in LabVIEW
59
CreatingandUsingTables 11.1
Exercises
CreateasimpleviewbasedontheexampletablesandruntheviewfromLabVIEW.
Tutorial: Database Communication in LabVIEW
12 Creatingandusing
StoredProcedures
Astoredprocedureisasubroutineavailabletoapplicationsaccessingarelationaldatabase
system.Typicalusesforstoredproceduresincludedatavalidation(integratedintothe
database)oraccesscontrolmechanisms.Furthermore,storedproceduresareusedto
consolidateandcentralizelogicthatwasoriginallyimplementedinapplications.Largeor
complexprocessingthatmightrequiretheexecutionofseveralSQLstatementsismoved
intostoredprocedures,andallapplicationscalltheproceduresonly.
AstoredprocedureisaprecompiledcollectionofSQLstatementsandoptionalcontrol-offlowstatements,similartoamacro.Eachdatabaseanddataprovidersupportsstored
proceduresdifferently.Storedproceduresofferthefollowingbenefitstoyourdatabase
applications:
Performance—StoredProceduresareusuallymoreefficientandfasterthanregularSQL
queriesbecauseSQLstatementsareparsedforsyntacticalaccuracyandprecompiledbythe
DBMSwhenthestoredprocedureiscreated.Also,combiningalargenumberofSQL
statementswithconditionallogicandparametersintoastoredprocedureallowsthe
procedurestoperformqueries,makedecisions,andreturnresultswithoutextratripstothe
databaseserver.
Maintainability—StoredProceduresisolatethelower-leveldatabasestructurefromthe
application.Aslongasthetablenames,columnnames,parameternames,andtypesdonot
changefromwhatisstatedinthestoredprocedure,youdonotneedtomodifythe
procedurewhenchangesaremadetothedatabaseschema.Storedproceduresarealsoa
waytosupportmodularSQLprogrammingbecauseafteryoucreateaprocedure,youand
otheruserscanreusethatprocedurewithoutknowingthedetailsofthetablesinvolved.
Security—Whencreatingtablesinadatabase,theDatabaseAdministratorcansetEXECUTE
permissionsonstoredprocedureswithoutgrantingSELECT,INSERT,UPDATE,andDELETE
permissionstousers.Therefore,thedatainthesetablesisprotectedfromuserswhoarenot
usingthestoredprocedures.
Storedproceduresaresimilartouser-definedfunctions.Themajordifferenceisthat
functionscanbeusedlikeanyotherexpressionwithinSQLstatements,whereasstored
proceduresmustbeinvokedusingtheCALLstatement.
60
61
CreatingandusingStoredProcedures 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:
Tutorial: Database Communication in LabVIEW
62
CreatingandusingStoredProcedures 12.1
Exercises
RuntheStoredProcedurecreatedabovefromLabVIEW.
Tutorial: Database Communication in LabVIEW
13 CreatingandUsing
Triggers
Adatabasetriggerisproceduralcodethatisautomaticallyexecutedinresponsetocertain
eventsonaparticulartableorviewinadatabase.Thetriggerismostlyusedforkeepingthe
integrityoftheinformationonthedatabase.Forexample,whenanewrecord(representing
anewworker)addedtotheemployeestable,newrecordsshouldbecreatedalsointhe
tablesofthetaxes,vacations,andsalaries.
Triggersarecommonlyusedto:
•
•
•
•
•
•
•
•
preventchanges(e.g.preventaninvoicefrombeingchangedafterit'sbeenmailed
out) 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-dataintemporary
tables) cannotperformcommitorrollbackoperationsbecausetheyarepartofthetriggering
SQLstatement cancancelarequestedoperation cancausemutatingtableerrors,iftheyarepoorlywritten.
63
64
CreatingandusingStoredProcedures MicrosoftSQLServersupportstriggerseitherafterorinsteadofaninsert,update,ordelete
operation.
Thesyntaxisasfollows:
CREATE TRIGGER <TriggerName>
FOR INSERT, UPDATE, DELETE
AS
… Create your Code here
GO
•
•
on <TableName>
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‘Telemark
UniversityCollege’
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
Tutorial: Database Communication in LabVIEW
65
CreatingandusingStoredProcedures Note!Notetheuseofatemporarytablecalled“INSERTED”.Thistemporarytablecontains
thelastinsertedrecordintotheSCHOOLtable
Note!InSQLyoudefineavariablelikethis
DECLARE
@myVariable <datatype>
Example:
DECLARE
@SchoolName varchar(10)
Note!Youhavetousethesymbol“@”beforethenameofthevariable!!!
BelowweseehowwecreateaTriggerfromthe“SQLServerManagementStudio”:
CheckiftheTriggerisworkingasexpected:
Procedure:
Step1:Checkthedatainyourtablebeforeyoudoanything,e.g.:
select * from SCHOOL
Tutorial: Database Communication in LabVIEW
66
CreatingandusingStoredProcedures Step2:Insertsometestdataintoyourtable,e.g.:
insert into SCHOOL (SchoolId, SchoolName) values (5, 'TUC')
Step3:CheckthedatahasbeenupdatedaccordingtoyourcodeintheTrigger:
select * from SCHOOL
→Asyouseethedatayouinsertedintothetablehasbeenautomaticallybeenchangedby
theTrigger
13.1
Exercises
CreateaTriggerthatadds“+47”toallPhonenumbersintheCUSTOMERtable.
TestandseeiftheTriggerworksproperlybyinsertingandupdatingsomedatainthe
CUSTOMERtable.
Tutorial: Database Communication in LabVIEW
14 Creatingandusing
Functions
InSQLdatabases,auser-definedfunctionprovidesamechanismforextendingthe
functionalityofthedatabaseserverbyaddingafunctionthatcanbeevaluatedinSQL
statements.TheSQLstandarddistinguishesbetweenscalarandtablefunctions.Ascalar
functionreturnsonlyasinglevalue(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
Exercises
Createasimplefunctionthatfindsnumberoforderforaspecificcustomeranduseitinthe
followingquery:
“Select FirstName, LastName, fn_NumberOfOrders(CustomerId) from CUSTOMER”
67
15 SQLToolkit
Ihavemadeasimpleandeasyto-useSQLToolkit.TheSQLToolkitisavailablefordownload
frommyBlog:http://home.hit.no/~hansha/
15.1
Installation
Theinstallationprocedureisasfollows:
1.
2.
3.
4.
5.
DownloadthezipfileSQLToolkit.zipfrommyBlog
Unzipthefile
Copy"SQLToolkit.mnu"to...\LabVIEW2009\menus\Categories\
Copy"SQLToolkit.llb"to...\LabVIEW2009\vi.lib\
TheSQLToolkitisreadytouseandintheFunctionspaletteinLabVIEWanewpalette
named"SQL"willappear.
TheSQLToolkitpaletteinavailableinLabVIEW:
TheSQLToolkitcontainsthefollowingVIs:
“SQLOpen.vi”-ThisVIopenaconnectiontothedatabasespecifiedintheConnection
string.Theconnectionstringmaybeasfollows: “PROVIDER=SQLOLEDB; DATA SOURCE=xxx;UID=xxx;PWD=xxx;DATABASE=xxx”
Youneedtoreplacethe“xxx”withtheparametersfromyourdatabase.
68
69
SQLToolkit “SQLSelect.vi”-ThisVIgetdatafromthedatabasespecifiedintheSQLQuery.The
outputisa2Dstringarraywithdata.
“SQLExecute.vi”-ThisVIexecutesaQuerywithnoreturnData,e.g.,anINSERT
statement
“SQLClose.vi”-ThisVIClosetheconnectiontothedatabaseopenedby"SQLOpen.vi"
Twoexamplesarealsoincluded:
“SQL–Example1.vi”–Thisexampleselectsdatafromatable.Theexampleuses“SQL
Select.vi”inordertogetdatafromthedatabase.
Frontpanel:
BlockDiagram:
Tutorial: Database Communication in LabVIEW
70
SQLToolkit “SQL–Example2.vi”–Thisexampleinsertsdataintoatable.Theexampleuses“SQL
Execute.vi”inordertoinsertdataintothedatabase.Nodataisreturned.
Frontpanel:
BlockDiagram:
Example:GetDataintoLabVIEWusingSQLToolkit
DownloadtheSQLtoolkitfromtheHomepageoftheDatabaseLabandfollowthe
instructionsintheReadMefile.
OntheFunctionspaletteonyourBlockDiagramthefollowingpaletteshouldappear:
Tutorial: Database Communication in LabVIEW
71
SQLToolkit HereisasimpleexampleofhowyougetdatafromthedatabaseintoLabVIEW:
Theprocedureisasfollows:
Step1:
Step2:
Tutorial: Database Communication in LabVIEW
72
SQLToolkit Step3and4:
Step5:
Tutorial: Database Communication in LabVIEW
73
SQLToolkit Step6:
Step7:
Tutorial: Database Communication in LabVIEW
74
SQLToolkit Step8:
Tutorial: Database Communication in LabVIEW
Hans-PetterHalvorsen,M.Sc.
E-mail:[email protected]
Blog:http://home.hit.no/~hansha/
UniversityCollegeofSoutheastNorway
www.usn.no