Database Overview - a Blog about Technology · Database Overview Hans-Petter Halvorsen, M.Sc. ......

Post on 26-Jul-2018

215 views 0 download

transcript

DatabaseOverview

Hans-PetterHalvorsen,M.Sc.

IntroductiontoDatabaseSystems,ERwin,SQLServer,SQL,etc.

Contents• DatabaseModelling/DesignusingERwin• GenerateSQLTableScriptusingERwin• GenerateTablesinSQLServerusingtheSQLScriptgeneratedbyERwin

• UseStructuredQueryLanguage(SQL)• CreateStoredProcedures,View,Triggers• DatabaseCommunicationinLabVIEW• DatabaseCommunicationinC#

NecessarySoftware

• ERwin (CAERwinDataModelerCommunityEdition,freedownloadfromInternet)

• SQLServer(Express)Edition(DownloadforfreefromInternetorDreamSpark:“SQLServerxxxx ExpresswithTools”)

• LabVIEW• DAQmxDriverSoftware• LabVIEWSQLToolkit(©Hans-PetterHalvorsen)• VisualStudio

MakesuretoinstallthenecessarySoftwarebeforeyougotothelaboratory!

Software

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

DatabaseSystems

Hans-PetterHalvorsen,M.Sc.

https://www.youtube.com/watch?v=n75iPNrzN-o

OldfashionDatabase(Data-storage)Systems

Nottoolongago,thiswastheonlydata-storagedevicemostcompaniesneeded.Thosedaysareover.

DatabaseSystemsADatabaseisastructuredwaytostorelotsofinformation.Theinformationisstoredindifferenttables.- “Everything”todayisstoredindatabases!Examples:• Bank/Accountsystems• InformationinWebpagessuchasFacebook,Wikipedia,YouTube,etc.

• Fronter,TimeEdit,etc.• …lotsofotherexamples!

Theory

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

MicrosoftSQLServerSQLServerconsists ofaDatabaseEngineandaManagementStudio.TheDatabaseEnginehasnographicalinterface- itisjustaservicerunninginthebackgroundofyourcomputer(preferableontheserver).TheManagementStudioisgraphicaltoolforconfiguring andviewingtheinformation inthedatabase.Itcanbeinstalledontheserverorontheclient(orboth).

SoftwareSoftware

ERwin

Hans-PetterHalvorsen,M.Sc.

DatabaseDesign&Modelling

https://www.youtube.com/watch?v=P3n6hRNup8Y

CAERwinDataModelerCommunityEdition• Free!• Max25Tables(goodenoughforourpurpose)• Downloadhere:http://erwin.com/products/data-modeler/community-edition

Software

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

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!

IntroductiontoERwinOpenERwinandselectFile->New...Thefollowingwindowappears(NewModel):

SelecttheDatabaseTypeandVersionyoushalluse

Makesuretoselect“Logical/Physical”Model

Software

IntroductiontoERwin

“Landscape”orientationisrecommended

IntroductiontoERwin

TrytocreatethefollowingTables,Columns,PrimaryKeysandForeignKeysusingERwin:

IntroductiontoERwinUsethe“Entity”Tool inorder

toCreateNewTables

Use<Tab>and<Enter>inordertogivetheTablesaNameandtocreateColumns.

Usethe<Arrows>toswitchbetweentheColumns insideaTable

How-To:CreateTablesandColumns

IntroductiontoERwinUsethe“Relationship”Toolinorder

toCreateaPrimaryKey(PK)–ForeignKey(FK)Relationship

ClickfirstonthePKtableandthenontheFKtableusing the“Relationship”Tool.TheRelationshipConnectionandtheFK

column itselfisthenCreatedAutomatically

How-To:CreatePrimaryKey(PK)– ForeignKey(FK)Relationships:

SettingDataTypes(PhysicalModel)

YoumayalsoDouble-click(orRight-clickandselectTable/ColumnProperties)onTablesandColumns inorder tochangedifferent

Attributes,eg.DataTypes,etc.

MakesuretosetproperDataTypes

20

FinalResults:

CreatingTABLEScript

21

Makesureyou areusingthePhysicalModel

How-To:CreateaSQLScriptSelect“ForwardEngineering”

and“Schema...”

Select/DeselectdifferentOptionsinordertomakeyourscriptthewayyouwant.Click “Preview”in

ordertoseetheresults.

Click“Save”whenyouaresatisfiedwithyourScript

1

2

3

4

22

TrytoCreatethisExampleusingERwin.FindproperDataTypesinthePhysicalModel

DatabaseDesignExercise

Congratulations!- YouarefinishedwiththeExample

SQLServer

Hans-PetterHalvorsen,M.Sc.

DatabaseImplementation

https://www.youtube.com/watch?v=SlR4KOhAG1U

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

26

StartInstallingSQLServer2014ExpresswithToolsStep1

Step2(JustClickNext)

Note!ThesescreenshotsarefromSQLServer2012– butSQLServer2014issimiliar

27

Step3(JustClickNext)

Step4(JustClickNext)

28

Step5(UseDefaultorchangetheNameifyouwantto)

Step6(JustClickNext)

29

Step7(Select“MixedMode”)

Step7b(useDefaultlocationorchangefolderfortheDatabaseFiles)

EnterPasswordfor“sa”userandmakesuretorememberit!!

“MixedMode”isrecommended

30

Step8(JustClickNext)

Step9– Finished!

HopefullyareallGreen(Succeeded)YouarenowreadytouseSQLServer

MicrosoftSQLServerManagementStudio

WriteyourQueryhere

TheresultfromyourQuery

YourDatabase

YourTables

YourSQLServer

Software

1

2

3

4

5

MicrosoftSQLServer– CreateaNewDatabase

32

Nameyoudatabase,e.g.,“SCHOOL”1

2

33TrytoCreatetheseTablesinSQLServer(eithermanuallyorfromtheScriptfromERwin)

DatabaseDesignExercise

OpenSQLServerandcreatea“NewDatabase...”1 SQLServer

2

OpentheSQLScriptinordertoinserttheTablesinSQLServer

3 YouareFinished. Youarereadytostartusingthe

database,insertingdata,etc.

35

MicrosoftSQLServer

Makesuretouncheckthisoption!

Doyougetanerrorwhentryingtochangeyourtables?

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

CreateTableswiththe“DatabaseDiagram”

37

YoumayselectexistingtablesorcreatenewTables

CreateNewTable

EnterColumns, selectDataTypes,PrimaryKeys,etc.

1 2

3

4

5

Congratulations!- YouarefinishedwiththeExample

StructuredQueryLanguageSQL

Hans-PetterHalvorsen,M.Sc.

WhatisSQL?• SQL– StructuredQueryLanguage• SQLisastandardlanguageforaccessingdatabases– andmanipulatedata

• SQLisnotcasesensitive

select SchoolId, Name from SCHOOL

ColumnsTable

Example:

Weusethe“SELECT”commandinordertogetdatafromtheDatabase

Theory

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

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

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

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:

SQLQueries

TrytoCreatethefollowingTableandDatausingSQL

TableName:CUSTOMER

INSERT

INSERTINTOCUSTOMER(CustomerName,ContactName,Address,City,PostalCode,Country)VALUES('Cardinal','TomB.Erichsen','Skagen21','Stavanger','4006','Norway');

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

UPDATETrytoWriteandExecutethefollowingQuery

UPDATECUSTOMERSETContactName='AlfredSchmidt',City='Hamburg'WHERECustomerName='AlfredsFutterkiste'

UpdateWarning!Becarefulwhenupdatingrecords.WhathappensifwehadomittedtheWHEREclause,intheexampleabove,likethis:

UPDATECUSTOMERSETContactName='AlfredSchmidt',City='Hamburg';

DELETETrytoWriteandExecutethefollowingQuery

DELETEFROMCUSTOMERWHERECustomerName='AlfredsFutterkiste'ANDContactName='MariaAnders'

Note!Itispossibletodeleteallrowsinatablewithoutdeletingthetable

DELETE*FROMCUSTOMER

Note!Becareful!AllDatawillbelost!!

Congratulations!- YouarefinishedwiththeExample

AdvancedSQLFeatures

Hans-PetterHalvorsen,M.Sc.

Views,StoredProcedures,TriggersandFunctions

https://www.youtube.com/watch?v=SHELF_iQUeU

AdvancedSQLFeatures• Views:Viewsarevirtualtablesforeasieraccesstodata

storedinmultipletables.• StoredProcedures:AStoredProcedureisaprecompiled

collectionofSQLstatements.Inastoredprocedureyoucanuseifsentence,declarevariables,etc.

• Triggers:Adatabasetriggeriscodethatisautomaticallyexecutedinresponsetocertaineventsonaparticulartableinadatabase.

• Functions:WithSQLandSQLServeryoucanuselotsofbuilt-infunctionsoryoumaycreateyourownfunctions

Theory

53

ItisassumedthatyoualreadyhavecreatedtheseTablesinaprevious task

54

selectSchoolName,CourseNamefromSCHOOLinnerjoinCOURSEonSCHOOL.SchoolId =COURSE.SchoolId

Example:

YoulinkPrimaryKeysandForeignKeystogether

TrythisExample

GetDatafrommultiple tablesinasingleQueryusingJoins

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

CreatingViewsusingtheEditor

AddnecessarytablesSavetheView

GraphicalInterfacewhereyoucanselectcolumnsyouneed

TrythisExample

4

1

2

3

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

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

Quiz

http://www.w3schools.com/quiztest/quiztest.asp?qtest=SQL

TestyourskillswiththisMultipleChoiceTest

WanttolearnmoreSQL?

Congratulations!- YouarefinishedwiththeExample

DatabaseCommunicationinLabVIEWLabVIEW

Hans-PetterHalvorsen,M.Sc.

https://www.youtube.com/watch?v=q0_2zPtBbeE

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!

ODBC– StepbyStepInstructions

64

TheNameofyourSQLServer

TheNameofyourODBCConnection

UseeitherWindowsorSQLServerauthentication(Windowsissimplesttouse!)

SelecttheDatabaseyouareusing

Testyourconnectiontoseeifitsworks

SQLServerConfigurationManager

MakesuretoEnable theseProtocols!

IfnottheDatabaseCommunicationfromLabVIEWmaynotworkproperly!

LabVIEWSQLToolkit

http://home.hit.no/~hansha/documents/labview/code/SQLToolkit.zip

ForEasyDatabaseCommunicationwithLabVIEW

©Hans-PetterHalvorsenDownloadforfreehere:

SoftwareSoftware

LabVIEWSQLToolkit

67

Example1:GetDatafromDatabaseintoLabVIEW:

Example2:WriteDatatoDatabasefromLabVIEW:

EasyAccesstoDatabaseSystemsfromLabVIEW

YourODBCConnection

2DTablewithData

1

Query

Query

2 3

1 2 3

TrytheseExamples

LabVIEWSQLToolkitEasyAccesstoDatabaseSystemsfromLabVIEW

AlternativeSolution:TypeintheConnectionStringforyourDatabase

Note!Whenusing thismethod,youdontneedtocreateanODBCConnection first!

YourPasswordforthesauser

YourSQLServerInstance

TypeyourDatabasehere

YourSQLQuery

DatabaseCommunicationinLabVIEW

69

InthisExampleweusetheNITC-01Thermocoupledeviceinorder tologTemperaturedatatoaSQLServerDatabasefromLabVIEW.

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

LabVIEWExample MainProgram

Pop-upDialogBox

SubVIforSavingDatatotheDatabase

SubVIforRetrievingDatafromtheDatabase

MainProgram

UpdateGUI

VIPropertiesSettings

VIPropertiesSettings

Congratulations!- YouarefinishedwiththeExample

DatabaseCommunicationinVisualStudio/C#VisualStudio

Hans-PetterHalvorsen,M.Sc.

ASP.NETWebForm AppExample

ASP.NETisaWebFrameworkavailablefromVisualStudio.Easilyexplained,itisjusta“Template”forcreatingWebPagesusingC#

Database

78

ThisisourExampleDatabase(DesignedwithERwin)

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

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

--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

ASP.NETWebFormCreateaNewProjectinVisualStudio

83

AddaNewWebForm(“Books.aspx”)

Books.aspx

Right-clickintheSolutionsExplorerandselect“AddNewItem”

CreatethefollowingGUI(“Books.aspx”)

GridView (DragandDropfromtheToolbox)

Header

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!!

86

CreateDatabaseCode– CreateanewClass(“Books.cs”)

Books.cs

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)

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

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

Congratulations!- YouarefinishedwiththeExample

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

Congratulations!- YouarefinishedwiththeExample

Congratulations!- Youarefinishedwithall theExamplesinthisTutorial

Hans-PetterHalvorsen,M.Sc.

UniversityCollegeofSoutheastNorwaywww.usn.no

E-mail:hans.p.halvorsen@hit.noBlog:http://home.hit.no/~hansha/