Database Overview - halvorsen.blog › documents › technology › resources... · Microsoft SQL...
Transcript of Database Overview - halvorsen.blog › documents › technology › resources... · Microsoft SQL...
![Page 1: Database Overview - halvorsen.blog › documents › technology › resources... · Microsoft SQL Server SQL Server consists of a Database Engine and a Management Studio. The Database](https://reader033.fdocuments.us/reader033/viewer/2022053014/5f10cf097e708231d44aeb2c/html5/thumbnails/1.jpg)
DatabaseOverview
Hans-PetterHalvorsen,M.Sc.
IntroductiontoDatabaseSystems,ERwin,SQLServer,SQL,etc.
![Page 2: Database Overview - halvorsen.blog › documents › technology › resources... · Microsoft SQL Server SQL Server consists of a Database Engine and a Management Studio. The Database](https://reader033.fdocuments.us/reader033/viewer/2022053014/5f10cf097e708231d44aeb2c/html5/thumbnails/2.jpg)
Contents• DatabaseModelling/DesignusingERwin• GenerateSQLTableScriptusingERwin• GenerateTablesinSQLServerusingtheSQLScriptgeneratedbyERwin
• UseStructuredQueryLanguage(SQL)• CreateStoredProcedures,View,Triggers• DatabaseCommunicationinLabVIEW• DatabaseCommunicationinC#
![Page 3: Database Overview - halvorsen.blog › documents › technology › resources... · Microsoft SQL Server SQL Server consists of a Database Engine and a Management Studio. The Database](https://reader033.fdocuments.us/reader033/viewer/2022053014/5f10cf097e708231d44aeb2c/html5/thumbnails/3.jpg)
NecessarySoftware
• ERwin (CAERwinDataModelerCommunityEdition,freedownloadfromInternet)
• SQLServer(Express)Edition(DownloadforfreefromInternetorDreamSpark:“SQLServerxxxx ExpresswithTools”)
• LabVIEW• DAQmxDriverSoftware• LabVIEWSQLToolkit(©Hans-PetterHalvorsen)• VisualStudio
MakesuretoinstallthenecessarySoftwarebeforeyougotothelaboratory!
Software
![Page 4: Database Overview - halvorsen.blog › documents › technology › resources... · Microsoft SQL Server SQL Server consists of a Database Engine and a Management Studio. The Database](https://reader033.fdocuments.us/reader033/viewer/2022053014/5f10cf097e708231d44aeb2c/html5/thumbnails/4.jpg)
RecommendedLitterature• Tutorial:IntroductiontoLabVIEW
http://home.hit.no/~hansha/?page=labview• Tutorial:IntroductiontoDatabaseSystems
http://home.hit.no/~hansha/?tutorial=database• Tutorial:StructuredQueryLanguage(SQL)
http://home.hit.no/~hansha/?tutorial=sql• Tutorial:DatabaseCommunicationinLabVIEW
http://home.hit.no/~hansha/?tutorial=database_labview• Tutorial:UsingSQLServerinC#• Tutorial:IntroductiontoVisualStudioandC#
http://home.hit.no/~hansha/?tutorial=csharp• Tutorial:DataAcquisitioninLabVIEW
http://home.hit.no/~hansha/?tutorial=daq
![Page 5: Database Overview - halvorsen.blog › documents › technology › resources... · Microsoft SQL Server SQL Server consists of a Database Engine and a Management Studio. The Database](https://reader033.fdocuments.us/reader033/viewer/2022053014/5f10cf097e708231d44aeb2c/html5/thumbnails/5.jpg)
DatabaseSystems
Hans-PetterHalvorsen,M.Sc.
https://www.youtube.com/watch?v=n75iPNrzN-o
![Page 6: Database Overview - halvorsen.blog › documents › technology › resources... · Microsoft SQL Server SQL Server consists of a Database Engine and a Management Studio. The Database](https://reader033.fdocuments.us/reader033/viewer/2022053014/5f10cf097e708231d44aeb2c/html5/thumbnails/6.jpg)
OldfashionDatabase(Data-storage)Systems
Nottoolongago,thiswastheonlydata-storagedevicemostcompaniesneeded.Thosedaysareover.
![Page 7: Database Overview - halvorsen.blog › documents › technology › resources... · Microsoft SQL Server SQL Server consists of a Database Engine and a Management Studio. The Database](https://reader033.fdocuments.us/reader033/viewer/2022053014/5f10cf097e708231d44aeb2c/html5/thumbnails/7.jpg)
DatabaseSystemsADatabaseisastructuredwaytostorelotsofinformation.Theinformationisstoredindifferenttables.- “Everything”todayisstoredindatabases!Examples:• Bank/Accountsystems• InformationinWebpagessuchasFacebook,Wikipedia,YouTube,etc.
• Fronter,TimeEdit,etc.• …lotsofotherexamples!
Theory
![Page 8: Database Overview - halvorsen.blog › documents › technology › resources... · Microsoft SQL Server SQL Server consists of a Database Engine and a Management Studio. The Database](https://reader033.fdocuments.us/reader033/viewer/2022053014/5f10cf097e708231d44aeb2c/html5/thumbnails/8.jpg)
DatabaseManagementSystems(DBMS)• MicrosoftSQLServer
– Enterprise,Developerversions,etc.(Professionaluse)– Expressversionisfreeofcharge
• Oracle• MySQL (ownedbyOracle,butpreviouslyownedbySun
Microsystems)- MySQLcanbeusedfreeofcharge(opensourcelicense),WebsitesthatuseMySQL:YouTube,Wikipedia,Facebook
• MicrosoftAccess• IBMDB2• Sybase,etc.(wehavehundredsdifferentDBMS)
WewilluseSQLserverbecauseitisverypopular intheindustry today,andwecanuseitforfreeviatheMicrosoftDreamSparkPremiumSubscription – whichisavailableforthestudentsandstaffatTelemarkUniversityCollege,orusetheExpressversionwhichisavailableforfreeforeverybody.
Theory
![Page 9: Database Overview - halvorsen.blog › documents › technology › resources... · Microsoft SQL Server SQL Server consists of a Database Engine and a Management Studio. The Database](https://reader033.fdocuments.us/reader033/viewer/2022053014/5f10cf097e708231d44aeb2c/html5/thumbnails/9.jpg)
MicrosoftSQLServerSQLServerconsists ofaDatabaseEngineandaManagementStudio.TheDatabaseEnginehasnographicalinterface- itisjustaservicerunninginthebackgroundofyourcomputer(preferableontheserver).TheManagementStudioisgraphicaltoolforconfiguring andviewingtheinformation inthedatabase.Itcanbeinstalledontheserverorontheclient(orboth).
SoftwareSoftware
![Page 10: Database Overview - halvorsen.blog › documents › technology › resources... · Microsoft SQL Server SQL Server consists of a Database Engine and a Management Studio. The Database](https://reader033.fdocuments.us/reader033/viewer/2022053014/5f10cf097e708231d44aeb2c/html5/thumbnails/10.jpg)
ERwin
Hans-PetterHalvorsen,M.Sc.
DatabaseDesign&Modelling
https://www.youtube.com/watch?v=P3n6hRNup8Y
![Page 11: Database Overview - halvorsen.blog › documents › technology › resources... · Microsoft SQL Server SQL Server consists of a Database Engine and a Management Studio. The Database](https://reader033.fdocuments.us/reader033/viewer/2022053014/5f10cf097e708231d44aeb2c/html5/thumbnails/11.jpg)
CAERwinDataModelerCommunityEdition• Free!• Max25Tables(goodenoughforourpurpose)• Downloadhere:http://erwin.com/products/data-modeler/community-edition
Software
![Page 12: Database Overview - halvorsen.blog › documents › technology › resources... · Microsoft SQL Server SQL Server consists of a Database Engine and a Management Studio. The Database](https://reader033.fdocuments.us/reader033/viewer/2022053014/5f10cf097e708231d44aeb2c/html5/thumbnails/12.jpg)
DatabaseDesign– ERDiagramERDiagram(Entity-RelationshipDiagram)• UsedforDesignandModelingofDatabases.• SpecifyTablesandrelationship betweenthem(PrimaryKeysandForeignKeys)
PrimaryKey PrimaryKey ForeignKey
TableName
TableName
RelationalDatabase.InarelationaldatabaseallthetableshaveoneormorerelationwitheachotherusingPrimaryKeys(PK)andForeignKeys(FK).Note!Youcanonly haveonePKinatable,butyoumayhaveseveralFK’s.
ColumnNames
Example:
Theory
![Page 13: Database Overview - halvorsen.blog › documents › technology › resources... · Microsoft SQL Server SQL Server consists of a Database Engine and a Management Studio. The Database](https://reader033.fdocuments.us/reader033/viewer/2022053014/5f10cf097e708231d44aeb2c/html5/thumbnails/13.jpg)
Database- “BestPractice”• Tables:Useuppercaseandsingular formintablenames– notplural,e.g.,
“STUDENT”(not“students”)• Columns:UsePascalnotation,e.g.,“StudentId”• PrimaryKey:
• Ifthetablenameis“COURSE”,namethePrimaryKeycolumn“CourseId”,etc.• “Always”useInteger andIdentity(1,1) forPrimaryKeys.UseUNIQUE
constraintforothercolumnsthatneedstobeunique,e.g.“RoomNumber”• SpecifyRequired Columns(NOTNULL)– i.e.,whichcolumnsthatneedtohave
dataornot• Standardizeonfew/theseDataTypes:int,float,varchar(x),datetime,bit• UseEnglishfortableandcolumnnames• Avoidabbreviations!(Use“RoomNumber”– not“RoomNo”,“RoomNr”,...)
Itisrecommended thatyoufollowtheseguidelines!
![Page 14: Database Overview - halvorsen.blog › documents › technology › resources... · Microsoft SQL Server SQL Server consists of a Database Engine and a Management Studio. The Database](https://reader033.fdocuments.us/reader033/viewer/2022053014/5f10cf097e708231d44aeb2c/html5/thumbnails/14.jpg)
IntroductiontoERwinOpenERwinandselectFile->New...Thefollowingwindowappears(NewModel):
SelecttheDatabaseTypeandVersionyoushalluse
Makesuretoselect“Logical/Physical”Model
Software
![Page 15: Database Overview - halvorsen.blog › documents › technology › resources... · Microsoft SQL Server SQL Server consists of a Database Engine and a Management Studio. The Database](https://reader033.fdocuments.us/reader033/viewer/2022053014/5f10cf097e708231d44aeb2c/html5/thumbnails/15.jpg)
IntroductiontoERwin
“Landscape”orientationisrecommended
![Page 16: Database Overview - halvorsen.blog › documents › technology › resources... · Microsoft SQL Server SQL Server consists of a Database Engine and a Management Studio. The Database](https://reader033.fdocuments.us/reader033/viewer/2022053014/5f10cf097e708231d44aeb2c/html5/thumbnails/16.jpg)
IntroductiontoERwin
TrytocreatethefollowingTables,Columns,PrimaryKeysandForeignKeysusingERwin:
![Page 17: Database Overview - halvorsen.blog › documents › technology › resources... · Microsoft SQL Server SQL Server consists of a Database Engine and a Management Studio. The Database](https://reader033.fdocuments.us/reader033/viewer/2022053014/5f10cf097e708231d44aeb2c/html5/thumbnails/17.jpg)
IntroductiontoERwinUsethe“Entity”Tool inorder
toCreateNewTables
Use<Tab>and<Enter>inordertogivetheTablesaNameandtocreateColumns.
Usethe<Arrows>toswitchbetweentheColumns insideaTable
How-To:CreateTablesandColumns
![Page 18: Database Overview - halvorsen.blog › documents › technology › resources... · Microsoft SQL Server SQL Server consists of a Database Engine and a Management Studio. The Database](https://reader033.fdocuments.us/reader033/viewer/2022053014/5f10cf097e708231d44aeb2c/html5/thumbnails/18.jpg)
IntroductiontoERwinUsethe“Relationship”Toolinorder
toCreateaPrimaryKey(PK)–ForeignKey(FK)Relationship
ClickfirstonthePKtableandthenontheFKtableusing the“Relationship”Tool.TheRelationshipConnectionandtheFK
column itselfisthenCreatedAutomatically
How-To:CreatePrimaryKey(PK)– ForeignKey(FK)Relationships:
![Page 19: Database Overview - halvorsen.blog › documents › technology › resources... · Microsoft SQL Server SQL Server consists of a Database Engine and a Management Studio. The Database](https://reader033.fdocuments.us/reader033/viewer/2022053014/5f10cf097e708231d44aeb2c/html5/thumbnails/19.jpg)
SettingDataTypes(PhysicalModel)
YoumayalsoDouble-click(orRight-clickandselectTable/ColumnProperties)onTablesandColumns inorder tochangedifferent
Attributes,eg.DataTypes,etc.
MakesuretosetproperDataTypes
![Page 20: Database Overview - halvorsen.blog › documents › technology › resources... · Microsoft SQL Server SQL Server consists of a Database Engine and a Management Studio. The Database](https://reader033.fdocuments.us/reader033/viewer/2022053014/5f10cf097e708231d44aeb2c/html5/thumbnails/20.jpg)
20
FinalResults:
![Page 21: Database Overview - halvorsen.blog › documents › technology › resources... · Microsoft SQL Server SQL Server consists of a Database Engine and a Management Studio. The Database](https://reader033.fdocuments.us/reader033/viewer/2022053014/5f10cf097e708231d44aeb2c/html5/thumbnails/21.jpg)
CreatingTABLEScript
21
Makesureyou areusingthePhysicalModel
How-To:CreateaSQLScriptSelect“ForwardEngineering”
and“Schema...”
Select/DeselectdifferentOptionsinordertomakeyourscriptthewayyouwant.Click “Preview”in
ordertoseetheresults.
Click“Save”whenyouaresatisfiedwithyourScript
1
2
3
4
![Page 22: Database Overview - halvorsen.blog › documents › technology › resources... · Microsoft SQL Server SQL Server consists of a Database Engine and a Management Studio. The Database](https://reader033.fdocuments.us/reader033/viewer/2022053014/5f10cf097e708231d44aeb2c/html5/thumbnails/22.jpg)
22
TrytoCreatethisExampleusingERwin.FindproperDataTypesinthePhysicalModel
DatabaseDesignExercise
![Page 23: Database Overview - halvorsen.blog › documents › technology › resources... · Microsoft SQL Server SQL Server consists of a Database Engine and a Management Studio. The Database](https://reader033.fdocuments.us/reader033/viewer/2022053014/5f10cf097e708231d44aeb2c/html5/thumbnails/23.jpg)
Congratulations!- YouarefinishedwiththeExample
![Page 24: Database Overview - halvorsen.blog › documents › technology › resources... · Microsoft SQL Server SQL Server consists of a Database Engine and a Management Studio. The Database](https://reader033.fdocuments.us/reader033/viewer/2022053014/5f10cf097e708231d44aeb2c/html5/thumbnails/24.jpg)
SQLServer
Hans-PetterHalvorsen,M.Sc.
DatabaseImplementation
https://www.youtube.com/watch?v=SlR4KOhAG1U
![Page 25: Database Overview - halvorsen.blog › documents › technology › resources... · Microsoft SQL Server SQL Server consists of a Database Engine and a Management Studio. The Database](https://reader033.fdocuments.us/reader033/viewer/2022053014/5f10cf097e708231d44aeb2c/html5/thumbnails/25.jpg)
SQLServer2014InstallationSQLServerhasdifferentEditionsandInstallationPackages.Herewewillgothrough theinstallationofSQLServer2014ExpresswithTools.Preparation1:DownloadInstallationPackage(SQLServer2014ExpresswithTools)fromInternetorDreamSparks.Preparation2:AreyouusingWindows8/10?– Youmayneedtoinstallthe.NETFramework3.5inadvance:
Note!Ittakessometimetodownload, somakesuretodo itbeforetheLabWork inClass!!
• GotoSettings.Choose ControlPanelthenchoose Programs.• ClickTurnWindows featuresonoroff,andtheuserwillsee
Windows featurewindow.• Youcanenablethisfeaturebyclickon.NETFramework3.5(include
.NET2.0and3.0)selectitandclickOK.Afterthisstep,itwilldownload theentirepackagefrominternetandinstallthe.NETFramework3.5feature.
Software
![Page 26: Database Overview - halvorsen.blog › documents › technology › resources... · Microsoft SQL Server SQL Server consists of a Database Engine and a Management Studio. The Database](https://reader033.fdocuments.us/reader033/viewer/2022053014/5f10cf097e708231d44aeb2c/html5/thumbnails/26.jpg)
26
StartInstallingSQLServer2014ExpresswithToolsStep1
Step2(JustClickNext)
Note!ThesescreenshotsarefromSQLServer2012– butSQLServer2014issimiliar
![Page 27: Database Overview - halvorsen.blog › documents › technology › resources... · Microsoft SQL Server SQL Server consists of a Database Engine and a Management Studio. The Database](https://reader033.fdocuments.us/reader033/viewer/2022053014/5f10cf097e708231d44aeb2c/html5/thumbnails/27.jpg)
27
Step3(JustClickNext)
Step4(JustClickNext)
![Page 28: Database Overview - halvorsen.blog › documents › technology › resources... · Microsoft SQL Server SQL Server consists of a Database Engine and a Management Studio. The Database](https://reader033.fdocuments.us/reader033/viewer/2022053014/5f10cf097e708231d44aeb2c/html5/thumbnails/28.jpg)
28
Step5(UseDefaultorchangetheNameifyouwantto)
Step6(JustClickNext)
![Page 29: Database Overview - halvorsen.blog › documents › technology › resources... · Microsoft SQL Server SQL Server consists of a Database Engine and a Management Studio. The Database](https://reader033.fdocuments.us/reader033/viewer/2022053014/5f10cf097e708231d44aeb2c/html5/thumbnails/29.jpg)
29
Step7(Select“MixedMode”)
Step7b(useDefaultlocationorchangefolderfortheDatabaseFiles)
EnterPasswordfor“sa”userandmakesuretorememberit!!
“MixedMode”isrecommended
![Page 30: Database Overview - halvorsen.blog › documents › technology › resources... · Microsoft SQL Server SQL Server consists of a Database Engine and a Management Studio. The Database](https://reader033.fdocuments.us/reader033/viewer/2022053014/5f10cf097e708231d44aeb2c/html5/thumbnails/30.jpg)
30
Step8(JustClickNext)
Step9– Finished!
HopefullyareallGreen(Succeeded)YouarenowreadytouseSQLServer
![Page 31: Database Overview - halvorsen.blog › documents › technology › resources... · Microsoft SQL Server SQL Server consists of a Database Engine and a Management Studio. The Database](https://reader033.fdocuments.us/reader033/viewer/2022053014/5f10cf097e708231d44aeb2c/html5/thumbnails/31.jpg)
MicrosoftSQLServerManagementStudio
WriteyourQueryhere
TheresultfromyourQuery
YourDatabase
YourTables
YourSQLServer
Software
1
2
3
4
5
![Page 32: Database Overview - halvorsen.blog › documents › technology › resources... · Microsoft SQL Server SQL Server consists of a Database Engine and a Management Studio. The Database](https://reader033.fdocuments.us/reader033/viewer/2022053014/5f10cf097e708231d44aeb2c/html5/thumbnails/32.jpg)
MicrosoftSQLServer– CreateaNewDatabase
32
Nameyoudatabase,e.g.,“SCHOOL”1
2
![Page 33: Database Overview - halvorsen.blog › documents › technology › resources... · Microsoft SQL Server SQL Server consists of a Database Engine and a Management Studio. The Database](https://reader033.fdocuments.us/reader033/viewer/2022053014/5f10cf097e708231d44aeb2c/html5/thumbnails/33.jpg)
33TrytoCreatetheseTablesinSQLServer(eithermanuallyorfromtheScriptfromERwin)
DatabaseDesignExercise
![Page 34: Database Overview - halvorsen.blog › documents › technology › resources... · Microsoft SQL Server SQL Server consists of a Database Engine and a Management Studio. The Database](https://reader033.fdocuments.us/reader033/viewer/2022053014/5f10cf097e708231d44aeb2c/html5/thumbnails/34.jpg)
OpenSQLServerandcreatea“NewDatabase...”1 SQLServer
2
OpentheSQLScriptinordertoinserttheTablesinSQLServer
3 YouareFinished. Youarereadytostartusingthe
database,insertingdata,etc.
![Page 35: Database Overview - halvorsen.blog › documents › technology › resources... · Microsoft SQL Server SQL Server consists of a Database Engine and a Management Studio. The Database](https://reader033.fdocuments.us/reader033/viewer/2022053014/5f10cf097e708231d44aeb2c/html5/thumbnails/35.jpg)
35
MicrosoftSQLServer
Makesuretouncheckthisoption!
Doyougetanerrorwhentryingtochangeyourtables?
![Page 36: Database Overview - halvorsen.blog › documents › technology › resources... · Microsoft SQL Server SQL Server consists of a Database Engine and a Management Studio. The Database](https://reader033.fdocuments.us/reader033/viewer/2022053014/5f10cf097e708231d44aeb2c/html5/thumbnails/36.jpg)
CreateTablesusingtheDesignerToolsinSQLServer
Evenifyoucando“everything”usingtheSQLlanguage, itissometimeseasiertodosomething inthedesigner toolsintheManagementStudio inSQLServer.Insteadofcreatingascriptyoumayaswelleasilyusethedesigner forcreatingtables,constraints,insertingdata,etc.
Select“NewTable…”:
Next,thetabledesignerpopsupwhereyoucanaddcolumns, datatypes,etc.
Inthisdesignerwemayalsospecifyconstraints,suchasprimarykeys,unique, foreignkeys,etc.
12
![Page 37: Database Overview - halvorsen.blog › documents › technology › resources... · Microsoft SQL Server SQL Server consists of a Database Engine and a Management Studio. The Database](https://reader033.fdocuments.us/reader033/viewer/2022053014/5f10cf097e708231d44aeb2c/html5/thumbnails/37.jpg)
CreateTableswiththe“DatabaseDiagram”
37
YoumayselectexistingtablesorcreatenewTables
CreateNewTable
EnterColumns, selectDataTypes,PrimaryKeys,etc.
1 2
3
4
5
![Page 38: Database Overview - halvorsen.blog › documents › technology › resources... · Microsoft SQL Server SQL Server consists of a Database Engine and a Management Studio. The Database](https://reader033.fdocuments.us/reader033/viewer/2022053014/5f10cf097e708231d44aeb2c/html5/thumbnails/38.jpg)
Congratulations!- YouarefinishedwiththeExample
![Page 39: Database Overview - halvorsen.blog › documents › technology › resources... · Microsoft SQL Server SQL Server consists of a Database Engine and a Management Studio. The Database](https://reader033.fdocuments.us/reader033/viewer/2022053014/5f10cf097e708231d44aeb2c/html5/thumbnails/39.jpg)
StructuredQueryLanguageSQL
Hans-PetterHalvorsen,M.Sc.
![Page 40: Database Overview - halvorsen.blog › documents › technology › resources... · Microsoft SQL Server SQL Server consists of a Database Engine and a Management Studio. The Database](https://reader033.fdocuments.us/reader033/viewer/2022053014/5f10cf097e708231d44aeb2c/html5/thumbnails/40.jpg)
WhatisSQL?• SQL– StructuredQueryLanguage• SQLisastandardlanguageforaccessingdatabases– andmanipulatedata
• SQLisnotcasesensitive
select SchoolId, Name from SCHOOL
ColumnsTable
Example:
Weusethe“SELECT”commandinordertogetdatafromtheDatabase
Theory
![Page 41: Database Overview - halvorsen.blog › documents › technology › resources... · Microsoft SQL Server SQL Server consists of a Database Engine and a Management Studio. The Database](https://reader033.fdocuments.us/reader033/viewer/2022053014/5f10cf097e708231d44aeb2c/html5/thumbnails/41.jpg)
SQL– StructuredQueryLanguage
• insert into STUDENT (Name , Number, SchoolId)values ('John Smith', '100005', 1)
• select SchoolId, Name from SCHOOL
• select * from SCHOOL where SchoolId > 100
• update STUDENT set Name='John Wayne' where StudentId=2
• delete from STUDENT where SchoolId=3
QueryExamples:
Wehave4differentQueryTypes:INSERT,SELECT,UPDATEand DELETE
Theory
![Page 42: Database Overview - halvorsen.blog › documents › technology › resources... · Microsoft SQL Server SQL Server consists of a Database Engine and a Management Studio. The Database](https://reader033.fdocuments.us/reader033/viewer/2022053014/5f10cf097e708231d44aeb2c/html5/thumbnails/42.jpg)
ImportantSQLCommands• SELECT- extractsdatafromadatabase• UPDATE- updatesdatainadatabase• DELETE- deletesdatafromadatabase• INSERTINTO- insertsnewdataintoadatabase
• CREATEDATABASE- createsanewdatabase• ALTERDATABASE- modifiesadatabase• CREATETABLE- createsanewtable• ALTERTABLE- modifiesatable• DROPTABLE- deletesatable• CREATEINDEX- createsanindex(searchkey)• DROPINDEX- deletesanindex
Theory
TheseareusedwhencreatingormodifyingexistingTables
Thesearemostusedinyourdailywork.Thesecommandsareusedtoinsertormodifydata
![Page 43: Database Overview - halvorsen.blog › documents › technology › resources... · Microsoft SQL Server SQL Server consists of a Database Engine and a Management Studio. The Database](https://reader033.fdocuments.us/reader033/viewer/2022053014/5f10cf097e708231d44aeb2c/html5/thumbnails/43.jpg)
SQL
DDL DML
StructuredQueryLanguage(SQL)
DataDefinition Language(DDL) DataManipulation Language(DML)
Create Drop
Rename Alter
CRUD
CREATETables DELETETables
RENAMETables ALTERTables
CreateRead
UpdateDelete
INSERTINTO
SELECT
UPDATE
DELETE
2maingroupsofSQLCommands
Mostusedindailywork
![Page 44: Database Overview - halvorsen.blog › documents › technology › resources... · Microsoft SQL Server SQL Server consists of a Database Engine and a Management Studio. The Database](https://reader033.fdocuments.us/reader033/viewer/2022053014/5f10cf097e708231d44aeb2c/html5/thumbnails/44.jpg)
CreateTablesusingSQLCREATE TABLE SCHOOL(
SchoolId int IDENTITY(1, 1) NOT NULL PRIMARY KEY,SchoolName varchar(50) NOT NULL UNIQUE,Description varchar(1000) NULL,Address varchar50) NULL,Phone varchar(50) NULL,PostCode varchar(50) NULL,PostAddress varchar(50) NULL,
) GO......
Example:
![Page 45: Database Overview - halvorsen.blog › documents › technology › resources... · Microsoft SQL Server SQL Server consists of a Database Engine and a Management Studio. The Database](https://reader033.fdocuments.us/reader033/viewer/2022053014/5f10cf097e708231d44aeb2c/html5/thumbnails/45.jpg)
SQLQueries
TrytoCreatethefollowingTableandDatausingSQL
TableName:CUSTOMER
![Page 46: Database Overview - halvorsen.blog › documents › technology › resources... · Microsoft SQL Server SQL Server consists of a Database Engine and a Management Studio. The Database](https://reader033.fdocuments.us/reader033/viewer/2022053014/5f10cf097e708231d44aeb2c/html5/thumbnails/46.jpg)
INSERT
INSERTINTOCUSTOMER(CustomerName,ContactName,Address,City,PostalCode,Country)VALUES('Cardinal','TomB.Erichsen','Skagen21','Stavanger','4006','Norway');
![Page 47: Database Overview - halvorsen.blog › documents › technology › resources... · Microsoft SQL Server SQL Server consists of a Database Engine and a Management Studio. The Database](https://reader033.fdocuments.us/reader033/viewer/2022053014/5f10cf097e708231d44aeb2c/html5/thumbnails/47.jpg)
SELECTTrytoWriteandExecutethefollowingQueries
SELECT*FROMCUSTOMER
SELECT*FROMCUSTOMERWHERECustomerID=1
SELECTCustomerName,CityFROMCUSTOMER
SELECTDISTINCTCityFROMCUSTOMER
SELECT*FROMCUSTOMERWHERECountry='Mexico'
Note!SQLisNOTcasesensitive:“select”isthesameas“SELECT”
SELECT*FROMCUSTOMERWHERECountry='Germany’ ANDCity='Berlin'
SELECT*FROMCUSTOMERWHERECity='Berlin’ORCity=’Luleå'
SELECT*FROMCUSTOMERORDERBYCountry
SELECT*FROMCUSTOMERORDERBYCountryDESC
![Page 48: Database Overview - halvorsen.blog › documents › technology › resources... · Microsoft SQL Server SQL Server consists of a Database Engine and a Management Studio. The Database](https://reader033.fdocuments.us/reader033/viewer/2022053014/5f10cf097e708231d44aeb2c/html5/thumbnails/48.jpg)
UPDATETrytoWriteandExecutethefollowingQuery
UPDATECUSTOMERSETContactName='AlfredSchmidt',City='Hamburg'WHERECustomerName='AlfredsFutterkiste'
UpdateWarning!Becarefulwhenupdatingrecords.WhathappensifwehadomittedtheWHEREclause,intheexampleabove,likethis:
UPDATECUSTOMERSETContactName='AlfredSchmidt',City='Hamburg';
![Page 49: Database Overview - halvorsen.blog › documents › technology › resources... · Microsoft SQL Server SQL Server consists of a Database Engine and a Management Studio. The Database](https://reader033.fdocuments.us/reader033/viewer/2022053014/5f10cf097e708231d44aeb2c/html5/thumbnails/49.jpg)
DELETETrytoWriteandExecutethefollowingQuery
DELETEFROMCUSTOMERWHERECustomerName='AlfredsFutterkiste'ANDContactName='MariaAnders'
Note!Itispossibletodeleteallrowsinatablewithoutdeletingthetable
DELETE*FROMCUSTOMER
Note!Becareful!AllDatawillbelost!!
![Page 50: Database Overview - halvorsen.blog › documents › technology › resources... · Microsoft SQL Server SQL Server consists of a Database Engine and a Management Studio. The Database](https://reader033.fdocuments.us/reader033/viewer/2022053014/5f10cf097e708231d44aeb2c/html5/thumbnails/50.jpg)
Congratulations!- YouarefinishedwiththeExample
![Page 51: Database Overview - halvorsen.blog › documents › technology › resources... · Microsoft SQL Server SQL Server consists of a Database Engine and a Management Studio. The Database](https://reader033.fdocuments.us/reader033/viewer/2022053014/5f10cf097e708231d44aeb2c/html5/thumbnails/51.jpg)
AdvancedSQLFeatures
Hans-PetterHalvorsen,M.Sc.
Views,StoredProcedures,TriggersandFunctions
https://www.youtube.com/watch?v=SHELF_iQUeU
![Page 52: Database Overview - halvorsen.blog › documents › technology › resources... · Microsoft SQL Server SQL Server consists of a Database Engine and a Management Studio. The Database](https://reader033.fdocuments.us/reader033/viewer/2022053014/5f10cf097e708231d44aeb2c/html5/thumbnails/52.jpg)
AdvancedSQLFeatures• Views:Viewsarevirtualtablesforeasieraccesstodata
storedinmultipletables.• StoredProcedures:AStoredProcedureisaprecompiled
collectionofSQLstatements.Inastoredprocedureyoucanuseifsentence,declarevariables,etc.
• Triggers:Adatabasetriggeriscodethatisautomaticallyexecutedinresponsetocertaineventsonaparticulartableinadatabase.
• Functions:WithSQLandSQLServeryoucanuselotsofbuilt-infunctionsoryoumaycreateyourownfunctions
Theory
![Page 53: Database Overview - halvorsen.blog › documents › technology › resources... · Microsoft SQL Server SQL Server consists of a Database Engine and a Management Studio. The Database](https://reader033.fdocuments.us/reader033/viewer/2022053014/5f10cf097e708231d44aeb2c/html5/thumbnails/53.jpg)
53
ItisassumedthatyoualreadyhavecreatedtheseTablesinaprevious task
![Page 54: Database Overview - halvorsen.blog › documents › technology › resources... · Microsoft SQL Server SQL Server consists of a Database Engine and a Management Studio. The Database](https://reader033.fdocuments.us/reader033/viewer/2022053014/5f10cf097e708231d44aeb2c/html5/thumbnails/54.jpg)
54
selectSchoolName,CourseNamefromSCHOOLinnerjoinCOURSEonSCHOOL.SchoolId =COURSE.SchoolId
Example:
YoulinkPrimaryKeysandForeignKeystogether
TrythisExample
GetDatafrommultiple tablesinasingleQueryusingJoins
![Page 55: Database Overview - halvorsen.blog › documents › technology › resources... · Microsoft SQL Server SQL Server consists of a Database Engine and a Management Studio. The Database](https://reader033.fdocuments.us/reader033/viewer/2022053014/5f10cf097e708231d44aeb2c/html5/thumbnails/55.jpg)
CreatingViewsusingSQLcodeIF EXISTS (SELECT name
FROM sysobjectsWHERE name = 'CourseData' AND type = 'V')
DROP VIEW CourseDataGO
CREATE VIEW CourseDataAS
SELECTSCHOOL.SchoolId, SCHOOL.SchoolName, COURSE.CourseId, COURSE.CourseName,COURSE.Description
FROMSCHOOL INNER JOIN COURSE ON SCHOOL.SchoolId = COURSE.SchoolIdGO
YoucanUsetheViewasanordinary tableinQueries:
AViewisa“virtual”tablethatcancontaindatafrommultipletables
InsidetheViewyoujointhedifferent tablestogetherusingtheJOIN operator
TheNameoftheView
CreateView:
UsingtheView:
Thispartisnotnecessary– butifyoumakeanychanges,youneedtodeletetheoldversionbeforeyoucanupdateit
TrytoCreatethisViewandmakesureitworks
select * from CourseData
1
2
![Page 56: Database Overview - halvorsen.blog › documents › technology › resources... · Microsoft SQL Server SQL Server consists of a Database Engine and a Management Studio. The Database](https://reader033.fdocuments.us/reader033/viewer/2022053014/5f10cf097e708231d44aeb2c/html5/thumbnails/56.jpg)
CreatingViewsusingtheEditor
AddnecessarytablesSavetheView
GraphicalInterfacewhereyoucanselectcolumnsyouneed
TrythisExample
4
1
2
3
![Page 57: Database Overview - halvorsen.blog › documents › technology › resources... · Microsoft SQL Server SQL Server consists of a Database Engine and a Management Studio. The Database](https://reader033.fdocuments.us/reader033/viewer/2022053014/5f10cf097e708231d44aeb2c/html5/thumbnails/57.jpg)
StoredProcedureIFEXISTS (SELECTname
FROMsysobjectsWHEREname = 'StudentGrade'AND type= 'P')
DROPPROCEDUREStudentGradeOG
CREATEPROCEDUREStudentGrade@Studentvarchar(50),@Coursevarchar(10),@Gradevarchar(1)
AS
DECLARE@StudentId int,@CourseId int
select@StudentId =StudentIdfromSTUDENTwhereStudentName=@Student
select@CourseId =CourseId fromCOURSEwhereCourseName=@Course
insertintoGRADE(StudentId,CourseId,Grade)values (@StudentId,@CourseId,@Grade)GO
execute StudentGrade 'John Wayne', 'SCE2006', 'B'
AStoredProcedureislikeaMethodinC#- itisapieceofcodewithSQLcommandsthatdoaspecifictask– andyoureuseit
InputArgumentsInternal/LocalVariables
ProcedureName
SQLCode(the“body”oftheStoredProcedure)
Note!Eachvariablestartswith@
CreateStoredProcedure:
UsingtheStoredProcedure:
Thispartisnotnecessary– butifyoumakeanychanges,youneedtodeletetheoldversionbeforeyoucanupdateit
TrytoCreatethisStoredProcedureandmakesureitworks
1
2
![Page 58: Database Overview - halvorsen.blog › documents › technology › resources... · Microsoft SQL Server SQL Server consists of a Database Engine and a Management Studio. The Database](https://reader033.fdocuments.us/reader033/viewer/2022053014/5f10cf097e708231d44aeb2c/html5/thumbnails/58.jpg)
TriggerIF EXISTS (SELECT name
FROM sysobjectsWHERE name = 'CalcAvgGrade' AND type = 'TR')
DROP TRIGGER CalgAvgGradeGO
CREATE TRIGGER CalcAvgGrade ON GRADEFOR UPDATE, INSERT, DELETEAS
DECLARE@StudentId int,@AvgGrade float
select @StudentId = StudentId from INSERTED
select @AvgGrade = AVG(Grade) from GRADE where StudentId = @StudentId
update STUDENT set TotalGrade = @AvgGrade where StudentId = @StudentId
GO
ATriggerisexecutedwhenyouinsert,updateordeletedatainaTablespecified intheTrigger.
InsidetheTriggeryoucanuseordinarySQLstatements,createvariables,etc.
NameoftheTrigger
SpecifywhichTabletheTriggershallworkon
Internal/LocalVariables
SQLCode(The“body”oftheTrigger)
SpecifywhatkindofoperationstheTriggershallacton
Note!“INSERTED”isatemporarilytablecontainingthelatestinserteddata,anditisveryhandy touseinsideatrigger
CreatetheTrigger:
Thispartisnotnecessary– butifyoumakeanychanges,youneedtodeletetheoldversionbeforeyoucanupdateit
TrytoCreatethisTriggerandmakesureitworks
![Page 59: Database Overview - halvorsen.blog › documents › technology › resources... · Microsoft SQL Server SQL Server consists of a Database Engine and a Management Studio. The Database](https://reader033.fdocuments.us/reader033/viewer/2022053014/5f10cf097e708231d44aeb2c/html5/thumbnails/59.jpg)
Quiz
http://www.w3schools.com/quiztest/quiztest.asp?qtest=SQL
TestyourskillswiththisMultipleChoiceTest
![Page 60: Database Overview - halvorsen.blog › documents › technology › resources... · Microsoft SQL Server SQL Server consists of a Database Engine and a Management Studio. The Database](https://reader033.fdocuments.us/reader033/viewer/2022053014/5f10cf097e708231d44aeb2c/html5/thumbnails/60.jpg)
WanttolearnmoreSQL?
![Page 61: Database Overview - halvorsen.blog › documents › technology › resources... · Microsoft SQL Server SQL Server consists of a Database Engine and a Management Studio. The Database](https://reader033.fdocuments.us/reader033/viewer/2022053014/5f10cf097e708231d44aeb2c/html5/thumbnails/61.jpg)
Congratulations!- YouarefinishedwiththeExample
![Page 62: Database Overview - halvorsen.blog › documents › technology › resources... · Microsoft SQL Server SQL Server consists of a Database Engine and a Management Studio. The Database](https://reader033.fdocuments.us/reader033/viewer/2022053014/5f10cf097e708231d44aeb2c/html5/thumbnails/62.jpg)
DatabaseCommunicationinLabVIEWLabVIEW
Hans-PetterHalvorsen,M.Sc.
https://www.youtube.com/watch?v=q0_2zPtBbeE
![Page 63: Database Overview - halvorsen.blog › documents › technology › resources... · Microsoft SQL Server SQL Server consists of a Database Engine and a Management Studio. The Database](https://reader033.fdocuments.us/reader033/viewer/2022053014/5f10cf097e708231d44aeb2c/html5/thumbnails/63.jpg)
ODBCODBC(OpenDatabaseConnectivity) isastandardizedinterface(API)foraccessingthedatabasefromaclient.Youcanusethisstandardtocommunicatewithdatabasesfromdifferentvendors, suchasOracle,SQLServer,etc.ThedesignersofODBCaimedtomakeitindependent ofprogramming languages,databasesystems,andoperatingsystems.ControlPanel→AdministrativeTools→DataSources(ODBC)
WewillusethisODBCConnection laterinLabVIEWinordertoopentheDatabaseConnection fromLabVIEW
Theory
Note!Makesuretousethe32bit versionoftheODBCTool!
![Page 64: Database Overview - halvorsen.blog › documents › technology › resources... · Microsoft SQL Server SQL Server consists of a Database Engine and a Management Studio. The Database](https://reader033.fdocuments.us/reader033/viewer/2022053014/5f10cf097e708231d44aeb2c/html5/thumbnails/64.jpg)
ODBC– StepbyStepInstructions
64
TheNameofyourSQLServer
TheNameofyourODBCConnection
UseeitherWindowsorSQLServerauthentication(Windowsissimplesttouse!)
SelecttheDatabaseyouareusing
Testyourconnectiontoseeifitsworks
![Page 65: Database Overview - halvorsen.blog › documents › technology › resources... · Microsoft SQL Server SQL Server consists of a Database Engine and a Management Studio. The Database](https://reader033.fdocuments.us/reader033/viewer/2022053014/5f10cf097e708231d44aeb2c/html5/thumbnails/65.jpg)
SQLServerConfigurationManager
MakesuretoEnable theseProtocols!
IfnottheDatabaseCommunicationfromLabVIEWmaynotworkproperly!
![Page 66: Database Overview - halvorsen.blog › documents › technology › resources... · Microsoft SQL Server SQL Server consists of a Database Engine and a Management Studio. The Database](https://reader033.fdocuments.us/reader033/viewer/2022053014/5f10cf097e708231d44aeb2c/html5/thumbnails/66.jpg)
LabVIEWSQLToolkit
http://home.hit.no/~hansha/documents/labview/code/SQLToolkit.zip
ForEasyDatabaseCommunicationwithLabVIEW
©Hans-PetterHalvorsenDownloadforfreehere:
SoftwareSoftware
![Page 67: Database Overview - halvorsen.blog › documents › technology › resources... · Microsoft SQL Server SQL Server consists of a Database Engine and a Management Studio. The Database](https://reader033.fdocuments.us/reader033/viewer/2022053014/5f10cf097e708231d44aeb2c/html5/thumbnails/67.jpg)
LabVIEWSQLToolkit
67
Example1:GetDatafromDatabaseintoLabVIEW:
Example2:WriteDatatoDatabasefromLabVIEW:
EasyAccesstoDatabaseSystemsfromLabVIEW
YourODBCConnection
2DTablewithData
1
Query
Query
2 3
1 2 3
TrytheseExamples
![Page 68: Database Overview - halvorsen.blog › documents › technology › resources... · Microsoft SQL Server SQL Server consists of a Database Engine and a Management Studio. The Database](https://reader033.fdocuments.us/reader033/viewer/2022053014/5f10cf097e708231d44aeb2c/html5/thumbnails/68.jpg)
LabVIEWSQLToolkitEasyAccesstoDatabaseSystemsfromLabVIEW
AlternativeSolution:TypeintheConnectionStringforyourDatabase
Note!Whenusing thismethod,youdontneedtocreateanODBCConnection first!
YourPasswordforthesauser
YourSQLServerInstance
TypeyourDatabasehere
YourSQLQuery
![Page 69: Database Overview - halvorsen.blog › documents › technology › resources... · Microsoft SQL Server SQL Server consists of a Database Engine and a Management Studio. The Database](https://reader033.fdocuments.us/reader033/viewer/2022053014/5f10cf097e708231d44aeb2c/html5/thumbnails/69.jpg)
DatabaseCommunicationinLabVIEW
69
InthisExampleweusetheNITC-01Thermocoupledeviceinorder tologTemperaturedatatoaSQLServerDatabasefromLabVIEW.
![Page 70: Database Overview - halvorsen.blog › documents › technology › resources... · Microsoft SQL Server SQL Server consists of a Database Engine and a Management Studio. The Database](https://reader033.fdocuments.us/reader033/viewer/2022053014/5f10cf097e708231d44aeb2c/html5/thumbnails/70.jpg)
LabVIEWSQLToolkitExampleIfwewanttosaveinputdatafromtheuserwecanusethe“FormatIntoString”function
executeCreateBook ‘LordoftheRings',‘J.R.R.Tolkien',Wiley',‘32-2-333-56',Fantasy'
The%s operatorwillbereplacedbythetextfromtheTextBox ontheFrontPanel.ForNumberswecanuse%d (Integer)or%f forFloating-point Number.
ResultingSQLQuery:
GUI/HMI
Code:2
1
3
![Page 71: Database Overview - halvorsen.blog › documents › technology › resources... · Microsoft SQL Server SQL Server consists of a Database Engine and a Management Studio. The Database](https://reader033.fdocuments.us/reader033/viewer/2022053014/5f10cf097e708231d44aeb2c/html5/thumbnails/71.jpg)
LabVIEWExample MainProgram
Pop-upDialogBox
![Page 72: Database Overview - halvorsen.blog › documents › technology › resources... · Microsoft SQL Server SQL Server consists of a Database Engine and a Management Studio. The Database](https://reader033.fdocuments.us/reader033/viewer/2022053014/5f10cf097e708231d44aeb2c/html5/thumbnails/72.jpg)
SubVIforSavingDatatotheDatabase
SubVIforRetrievingDatafromtheDatabase
MainProgram
UpdateGUI
![Page 73: Database Overview - halvorsen.blog › documents › technology › resources... · Microsoft SQL Server SQL Server consists of a Database Engine and a Management Studio. The Database](https://reader033.fdocuments.us/reader033/viewer/2022053014/5f10cf097e708231d44aeb2c/html5/thumbnails/73.jpg)
VIPropertiesSettings
![Page 74: Database Overview - halvorsen.blog › documents › technology › resources... · Microsoft SQL Server SQL Server consists of a Database Engine and a Management Studio. The Database](https://reader033.fdocuments.us/reader033/viewer/2022053014/5f10cf097e708231d44aeb2c/html5/thumbnails/74.jpg)
VIPropertiesSettings
![Page 75: Database Overview - halvorsen.blog › documents › technology › resources... · Microsoft SQL Server SQL Server consists of a Database Engine and a Management Studio. The Database](https://reader033.fdocuments.us/reader033/viewer/2022053014/5f10cf097e708231d44aeb2c/html5/thumbnails/75.jpg)
Congratulations!- YouarefinishedwiththeExample
![Page 76: Database Overview - halvorsen.blog › documents › technology › resources... · Microsoft SQL Server SQL Server consists of a Database Engine and a Management Studio. The Database](https://reader033.fdocuments.us/reader033/viewer/2022053014/5f10cf097e708231d44aeb2c/html5/thumbnails/76.jpg)
DatabaseCommunicationinVisualStudio/C#VisualStudio
Hans-PetterHalvorsen,M.Sc.
![Page 77: Database Overview - halvorsen.blog › documents › technology › resources... · Microsoft SQL Server SQL Server consists of a Database Engine and a Management Studio. The Database](https://reader033.fdocuments.us/reader033/viewer/2022053014/5f10cf097e708231d44aeb2c/html5/thumbnails/77.jpg)
ASP.NETWebForm AppExample
ASP.NETisaWebFrameworkavailablefromVisualStudio.Easilyexplained,itisjusta“Template”forcreatingWebPagesusingC#
![Page 78: Database Overview - halvorsen.blog › documents › technology › resources... · Microsoft SQL Server SQL Server consists of a Database Engine and a Management Studio. The Database](https://reader033.fdocuments.us/reader033/viewer/2022053014/5f10cf097e708231d44aeb2c/html5/thumbnails/78.jpg)
Database
78
ThisisourExampleDatabase(DesignedwithERwin)
![Page 79: Database Overview - halvorsen.blog › documents › technology › resources... · Microsoft SQL Server SQL Server consists of a Database Engine and a Management Studio. The Database](https://reader033.fdocuments.us/reader033/viewer/2022053014/5f10cf097e708231d44aeb2c/html5/thumbnails/79.jpg)
79
SQLScript- Tablesif not exists (select * from dbo.sysobjects where id = object_id(N'[AUTHOR]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)CREATE TABLE [AUTHOR](
[AuthorId] [int] IDENTITY(1, 1) NOT NULL PRIMARY KEY,[AuthorName] [varchar](50) NOT NULL UNIQUE,[Address] [varchar](50) NULL,[Phone] [varchar](50) NULL,[PostCode] [varchar](50) NULL,[PostAddress] [varchar](50) NULL,
)GO
if not exists (select * from dbo.sysobjects where id = object_id(N'[PUBLISHER]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)CREATE TABLE [PUBLISHER](
[PublisherId] [int] IDENTITY(1, 1) NOT NULL PRIMARY KEY,[PublisherName] [varchar](50) NOT NULL UNIQUE,[Description] [varchar](1000) NULL,[Address] [varchar](50) NULL,[Phone] [varchar](50) NULL,[PostCode] [varchar](50) NULL,[PostAddress] [varchar](50) NULL,[EMail] [varchar](50) NULL,
)GO
if not exists (select * from dbo.sysobjects where id = object_id(N'[CATEGORY]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)CREATE TABLE [CATEGORY](
[CategoryId] [int] IDENTITY(1, 1) NOT NULL PRIMARY KEY,[CategoryName] [varchar](50) NOT NULL UNIQUE,[Description] [varchar](1000) NULL,
)GO
if not exists (select * from dbo.sysobjects where id = object_id(N'[BOOK]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)CREATE TABLE [BOOK](
[BookId] [int] IDENTITY(1, 1) NOT NULL PRIMARY KEY,[Title] [varchar](50) NOT NULL UNIQUE,[ISBN] [varchar](20) NOT NULL,[PublisherId] [int] NOT NULL FOREIGN KEY REFERENCES [PUBLISHER] ([PublisherId]),[AuthorId] [int] NOT NULL FOREIGN KEY REFERENCES [AUTHOR] ([AuthorId]),[CategoryId] [int] NOT NULL FOREIGN KEY REFERENCES [CATEGORY] ([CategoryId]),[Description] [varchar](1000) NULL,[Year] [date] NULL,[Edition] [int] NULL,[AverageRating] [float] NULL,
)GO
![Page 80: Database Overview - halvorsen.blog › documents › technology › resources... · Microsoft SQL Server SQL Server consists of a Database Engine and a Management Studio. The Database](https://reader033.fdocuments.us/reader033/viewer/2022053014/5f10cf097e708231d44aeb2c/html5/thumbnails/80.jpg)
SQLScript– InsertsomeDataintotheTables--CATEGORY ----------------------------------INSERT INTO CATEGORY (CategoryName) VALUES ('Science')GOINSERT INTO CATEGORY (CategoryName) VALUES ('Programming')GOINSERT INTO CATEGORY (CategoryName) VALUES ('Novel')GO
--AUTHOR ----------------------------------INSERT INTO AUTHOR (AuthorName) VALUES ('Knut Hamsun')GOINSERT INTO AUTHOR (AuthorName) VALUES ('Gilbert Strang')GOINSERT INTO AUTHOR (AuthorName) VALUES ('J.R.R Tolkien')GOINSERT INTO AUTHOR (AuthorName) VALUES ('Dorf Bishop')GO
--PUBLISHER ----------------------------------INSERT INTO PUBLISHER (PublisherName) VALUES ('Prentice Hall')GOINSERT INTO PUBLISHER (PublisherName) VALUES ('Wiley')GOINSERT INTO PUBLISHER (PublisherName) VALUES ('McGraw-Hill')GO
![Page 81: Database Overview - halvorsen.blog › documents › technology › resources... · Microsoft SQL Server SQL Server consists of a Database Engine and a Management Studio. The Database](https://reader033.fdocuments.us/reader033/viewer/2022053014/5f10cf097e708231d44aeb2c/html5/thumbnails/81.jpg)
--BOOK ----------------------------------INSERT INTO BOOK (Title, ISBN, PublisherId, AuthorId, CategoryId) VALUES('Introduction to Linear Algebra','0-07-066781-0',(select PublisherId from PUBLISHER where PublisherName='Prentice Hall'),(select AuthorId from AUTHOR where AuthorName='Gilbert Strang'),(select CategoryId from CATEGORY where CategoryName='Science'))GO
INSERT INTO BOOK (Title, ISBN, PublisherId, AuthorId, CategoryId) VALUES('Modern Control System','1-08-890781-0',(select PublisherId from PUBLISHER where PublisherName='Wiley'),(select AuthorId from AUTHOR where AuthorName='Dorf Bishop'),(select CategoryId from CATEGORY where CategoryName='Programming'))GO
INSERT INTO BOOK (Title, ISBN, PublisherId, AuthorId, CategoryId) VALUES('The Lord of the Rings','2-09-066556-2',(select PublisherId from PUBLISHER where PublisherName='McGraw-Hill'),(select AuthorId from AUTHOR where AuthorName='J.R.R Tolkien'),(select CategoryId from CATEGORY where CategoryName='Novel'))GO
SQLScript– InsertsomeDataintotheTables
![Page 82: Database Overview - halvorsen.blog › documents › technology › resources... · Microsoft SQL Server SQL Server consists of a Database Engine and a Management Studio. The Database](https://reader033.fdocuments.us/reader033/viewer/2022053014/5f10cf097e708231d44aeb2c/html5/thumbnails/82.jpg)
ASP.NETWebFormCreateaNewProjectinVisualStudio
![Page 83: Database Overview - halvorsen.blog › documents › technology › resources... · Microsoft SQL Server SQL Server consists of a Database Engine and a Management Studio. The Database](https://reader033.fdocuments.us/reader033/viewer/2022053014/5f10cf097e708231d44aeb2c/html5/thumbnails/83.jpg)
83
AddaNewWebForm(“Books.aspx”)
Books.aspx
Right-clickintheSolutionsExplorerandselect“AddNewItem”
![Page 84: Database Overview - halvorsen.blog › documents › technology › resources... · Microsoft SQL Server SQL Server consists of a Database Engine and a Management Studio. The Database](https://reader033.fdocuments.us/reader033/viewer/2022053014/5f10cf097e708231d44aeb2c/html5/thumbnails/84.jpg)
CreatethefollowingGUI(“Books.aspx”)
GridView (DragandDropfromtheToolbox)
Header
![Page 85: Database Overview - halvorsen.blog › documents › technology › resources... · Microsoft SQL Server SQL Server consists of a Database Engine and a Management Studio. The Database](https://reader033.fdocuments.us/reader033/viewer/2022053014/5f10cf097e708231d44aeb2c/html5/thumbnails/85.jpg)
85
CreatethefollowingCode(“Books.aspx.cs”)using System.Web.Configuration;using DatabaseWebApp.Data;
...
public partial class BookList : System.Web.UI.Page{private string connectionString = WebConfigurationManager.ConnectionStrings["LibraryDBConnectionString"].ConnectionString;
void Page_Load(object sender, EventArgs e){
if (!IsPostBack){
FillBookGrid();}
}
private void FillBookGrid(){
List<Book> bookList = new List<Book>();Book book = new Book();
bookList = book.GetBooks(connectionString);
gridBookList.DataSource = bookList;gridBookList.DataBind();
}}
WeshallcreatetheConnectionString totheDatabaseinthe“Web.configpage”
ReferencetoourClassthatcommunicateswiththeDatabase
SeenextslidesforimplementationoftheBookClass
Note!!
![Page 86: Database Overview - halvorsen.blog › documents › technology › resources... · Microsoft SQL Server SQL Server consists of a Database Engine and a Management Studio. The Database](https://reader033.fdocuments.us/reader033/viewer/2022053014/5f10cf097e708231d44aeb2c/html5/thumbnails/86.jpg)
86
CreateDatabaseCode– CreateanewClass(“Books.cs”)
Books.cs
![Page 87: Database Overview - halvorsen.blog › documents › technology › resources... · Microsoft SQL Server SQL Server consists of a Database Engine and a Management Studio. The Database](https://reader033.fdocuments.us/reader033/viewer/2022053014/5f10cf097e708231d44aeb2c/html5/thumbnails/87.jpg)
87
CreatetheFollowingClassin“Books.cs”using System.Data.SqlClient;using System.Data.SqlTypes;using System.Data;
public class Book{
public int BookId { get; set; }public string Title { get; set; }public string Isbn { get; set; }public string PublisherName { get; set; }public string AuthorName { get; set; }public string CategoryName { get; set; }
public List<Book> GetBooks(string connectionString){
List<Book> bookList = new List<Book>();
SqlConnection con = new SqlConnection(connectionString);
string selectSQL = "select BookId, Title, Isbn, PublisherName, AuthorName, CategoryName from GetBookData";
con.Open();
SqlCommand cmd = new SqlCommand(selectSQL, con);
SqlDataReader dr = cmd.ExecuteReader();
if (dr != null){
while (dr.Read()){
Book book = new Book();
book.BookId = Convert.ToInt32(dr["BookId"]);book.Title = dr["Title"].ToString();book.Isbn = dr["ISBN"].ToString();book.PublisherName = dr["PublisherName"].ToString();book.AuthorName = dr["AuthorName"].ToString();book.CategoryName = dr["CategoryName"].ToString();
bookList.Add(book);}
}
return bookList;}
}
GetBookDataisaView(seenextslide)
![Page 88: Database Overview - halvorsen.blog › documents › technology › resources... · Microsoft SQL Server SQL Server consists of a Database Engine and a Management Studio. The Database](https://reader033.fdocuments.us/reader033/viewer/2022053014/5f10cf097e708231d44aeb2c/html5/thumbnails/88.jpg)
SQLScript– Views– “GetBookData”IF EXISTS (SELECT name
FROM sysobjectsWHERE name = 'GetBookData'AND type = 'V')
DROP VIEW GetBookDataGO
CREATE VIEW GetBookDataAS
SELECTBOOK.BookId,BOOK.Title,BOOK.ISBN,PUBLISHER.PublisherName,AUTHOR.AuthorName,CATEGORY.CategoryName
FROM BOOKINNER JOIN AUTHOR ON BOOK.AuthorId = AUTHOR.AuthorIdINNER JOIN PUBLISHER ON BOOK.PublisherId = PUBLISHER.PublisherIdINNER JOIN CATEGORY ON BOOK.CategoryId = CATEGORY.CategoryId
GO
![Page 89: Database Overview - halvorsen.blog › documents › technology › resources... · Microsoft SQL Server SQL Server consists of a Database Engine and a Management Studio. The Database](https://reader033.fdocuments.us/reader033/viewer/2022053014/5f10cf097e708231d44aeb2c/html5/thumbnails/89.jpg)
CreateDatabaseConnectionStringin“Web.config”<connectionStrings>
<add name="LibraryDBConnectionString"connectionString="Data Source=macwin8;Initial Catalog=BOOKS;Persist Security Info=True;User ID=sa;Password=xxx"providerName="System.Data.SqlClient" />
</connectionStrings>
Where“xxx”isyourSQLServerDatabasePassword
Finally,Runyourapplication:
Congratulations!Itworks!
YourDatabase
UserNameandPasswordforyourSQLServer
![Page 90: Database Overview - halvorsen.blog › documents › technology › resources... · Microsoft SQL Server SQL Server consists of a Database Engine and a Management Studio. The Database](https://reader033.fdocuments.us/reader033/viewer/2022053014/5f10cf097e708231d44aeb2c/html5/thumbnails/90.jpg)
Congratulations!- YouarefinishedwiththeExample
![Page 91: Database Overview - halvorsen.blog › documents › technology › resources... · Microsoft SQL Server SQL Server consists of a Database Engine and a Management Studio. The Database](https://reader033.fdocuments.us/reader033/viewer/2022053014/5f10cf097e708231d44aeb2c/html5/thumbnails/91.jpg)
TrytoCreateAdd,EditandDeleteaswell
StepbyStepGuide:http://home.hit.no/~hansha/documents/software/software_development/topics/resources/programming/exercises/Create%20Database%20WebForm%20App/Create%20Database%20WebForm%20App.pdf
![Page 92: Database Overview - halvorsen.blog › documents › technology › resources... · Microsoft SQL Server SQL Server consists of a Database Engine and a Management Studio. The Database](https://reader033.fdocuments.us/reader033/viewer/2022053014/5f10cf097e708231d44aeb2c/html5/thumbnails/92.jpg)
Congratulations!- YouarefinishedwiththeExample
![Page 93: Database Overview - halvorsen.blog › documents › technology › resources... · Microsoft SQL Server SQL Server consists of a Database Engine and a Management Studio. The Database](https://reader033.fdocuments.us/reader033/viewer/2022053014/5f10cf097e708231d44aeb2c/html5/thumbnails/93.jpg)
Congratulations!- Youarefinishedwithall theExamplesinthisTutorial
![Page 94: Database Overview - halvorsen.blog › documents › technology › resources... · Microsoft SQL Server SQL Server consists of a Database Engine and a Management Studio. The Database](https://reader033.fdocuments.us/reader033/viewer/2022053014/5f10cf097e708231d44aeb2c/html5/thumbnails/94.jpg)
Hans-PetterHalvorsen,M.Sc.
UniversityCollegeofSoutheastNorwaywww.usn.no
E-mail:[email protected]:http://home.hit.no/~hansha/