Database Systems Overview

advertisement
DatabaseSystems
S.Adams.Dilbert.Available:http://dilbert.com
Hans-PetterHalvorsen,M.Sc.
OldfashionDatabase(Data-storage)Systems
Nottoolongago,thiswastheonlydata-storagedevicemost
companiesneeded.Thosedaysareover.
2
Deployment
Maintenance
Testing
Implementation
TheSoftware
Development
Lifecycle
Design
Planning
Requirements
Analysis
DatabaseSystems
ADatabaseisastructuredwaytostorelotsofinformation.
Theinformationisstoredindifferenttables.
- “Everything”todayisstoredindatabases!
Examples:
• Bank/Accountsystems
• InformationinWebpagessuchasFacebook,Wikipedia,
YouTube,etc.
• Fronter,TimeEdit,etc.
• …lotsofotherexamples!
4
Example:
DatabaseERDiagram
5
S.Adams.Dilbert.Available:http://dilbert.com
6
DatabaseManagementSystems(DBMS)
•
MicrosoftSQLServer
– Enterprise, Developerversions, etc.(Professional use)
– Expressversionisfreeofcharge
•
•
•
•
•
•
•
•
Oracle
MySQL (ownedbyOracle,butpreviouslyownedbySunMicrosystems)MySQLcanbeusedfreeofcharge(opensourcelicense),Websitesthatuse
MySQL:YouTube,Wikipedia,Facebook
MicrosoftAccess
IBMDB2
Sybase
MariaDB
MongoDB
etc.
7
DatabaseTypes
• RelationDatabase/SQLDatabases
–
–
–
–
–
MicrosftSQLServer
Oracle
MySQL
MariaDB
etc.
• NoSQLDatabases
– MongoDB
– etc.
8
SQLvs.NoSQL
DatabaseTypes
9
DatabaseModelling
Hans-PetterHalvorsen,M.Sc.
DatabaseModelling
• Thelogicalstructureofthedatabase
• ERDiagram(EntityRelationship)
11
DatabaseDesign– ERDiagram
ERDiagram(Entity-RelationshipDiagram)
• UsedforDesignandModelingofDatabases.
• SpecifyTablesandrelationship betweenthem(PrimaryKeysandForeignKeys)
TableName
Example:
TableName
Column
Names
PrimaryKey
PrimaryKey
ForeignKey
RelationalDatabase.InarelationaldatabaseallthetableshaveoneormorerelationwitheachotherusingPrimaryKeys(PK)andForeignKeys(FK).Note!Youcan
onlyhaveonePKinatable,butyoumayhaveseveralFK’s.
DatabaseDesignTools
• Visio
• PowerDesigner
• CAERwin
– CAERwinDataModelerCommunityEdition
– CommunityEditionisFree,25objectslimit
– SupportforOracle,SQLServer,MySQL,ODBC,Sybase
• ToadDataModeler
• ASimpledesignerisalsoincludedwithSQLServer
(physicalmodel,notlogicalmodel)
13
Database- “BestPractice”
• Tables:Useuppercaseandsingular formintablenames– notplural,e.g.,
“STUDENT”(notstudents)
• 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!(UseRoomNumber– notRoomNo,RoomNr,...)
14
DatabaseDesign– MicrosoftVisio
WewilluseVisioto
DesignourDatabase
1
2
SelecttheproperTemplate
3
15
TableName
ERDiagramExample- Visio
PrimaryKey(PK)
Foreign Key(FK)
17
ERDiagramExampleusingbuilt-inDesignerinMicrosoftSQLServer
TableName
TableName
PK
FK
PK
PK-FKRelationship
TableName
PK
FK
TableName
PK
FK
FK
TableName
PK
FK
PK-FKRelationships
TableName
PK
FK
TableName
PK
FK
FK
PK– PrimaryKey,FK– ForeignKey
TableName
PK
FK
FK
18
Exercise– DatabaseModelling
• CreateaDatabasemodel(ERDiagram)ofa
LibrarySystem
• ALibrarySystemtypicallycontains
informationaboutBooks,Authors,Publisers,
etc.
• Useapropertool(Visio,ERwin,...)
Hans-PetterHalvorsen,M.Sc.
SQLServer
• Mainparts:SQLServerEngine+Management
Studio
• Latestversion:SQLServer2014
• SQLServerStandard,Developer,Web,Enterprise,
Datacenter,...
• FreeAlternative:SQLServerExpress
• SQLAzureDatabase– Cloud-basedversion
21
MicrosoftSQLServer
SQLServerconsistsofaDatabaseEngineandaManagementStudio. TheDatabaseEngine hasnographicalinterface- itisjustaservice
runninginthebackground ofyour computer(preferableontheserver).TheManagement Studio isgraphicaltoolforconfiguringandviewing
theinformationinthedatabase.Itcanbeinstalledon theserverorontheclient(orboth).
Thenewestversion ofMicrosoftSQL
Serveris“SQLServer2014”
22
MicrosoftSQLServer
3
4
YourSQLServer
1
2
WriteyourQueryhere
YourDatabase
Your
Tables
5
Theresultfrom yourQuery
23
MicrosoftSQLServer– CreateaNewDatabase
2
1
Nameyoudatabase,e.g.,
WEATHER_SYSTEM
24
MicrosoftSQLServer– TipsandTricks
Doyougetanerror
whentryingto
changeyourtables?
Makesuretouncheck
thisoption!
25
Exercise– SQLServer
• CreateanewDatabase(LIBRARY)
• Implementthedifferenttablesbasedonthe
ERdiagramyouhavecreated(BOOK,AUTHOR,
PUBLISHER,etc.)
SQL
StructuredQueryLanguage
Hans-PetterHalvorsen,M.Sc.
SQL– StructuredQuerylanguage
ADatabaseComputerLanguagedesignedforManagingDatain
RelationalDatabaseManagementSystems(RDBMS)
QueryExamples:
•
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
Wehave4differentQueryTypes(CRUD):INSERT,SELECT,UPDATEand DELETE
CRUD – Create(Insert),Read(Select),UpdateandDelete
28
CreateTablesusingtheDesignerToolsinSQLServer
Evenifyoucando “everything”usingtheSQLlanguage, itissometimeseasiertodo
something inthedesigner toolsintheManagement Studio inSQLServer.
Insteadofcreatingascriptyoumayaswelleasilyusethedesigner forcreatingtables,
constraints,inserting data,etc.
1
Select“NewTable…”:
2
Next,thetabledesigner popsupwhereyou
canaddcolumns, datatypes,etc.
Inthisdesigner wemayalsospecifyconstraints,suchas
primarykeys,unique, foreign keys,etc.
29
CreateTableswiththe“DatabaseDiagram”
2
1
Youmayselect
existingtablesor
createnewTables
CreateNewTable
3
5
4
EnterColumns, selectDataTypes,
PrimaryKeys,etc.
30
if not exists (select * from dbo.sysobjects where id = object_id(N'[SCHOOL]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
CREATE TABLE [SCHOOL]
(
[SchoolId] [int] IDENTITY(1, 1) NOT NULL PRIMARY KEY,
[SchoolName] [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,
) GO
CreateTables
usingSQL
if not exists (select * from dbo.sysobjects where id = object_id(N'[CLASS]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
CREATE TABLE [CLASS]
(
[ClassId] [int] IDENTITY(1, 1) NOT NULL PRIMARY KEY,
[SchoolId] [int] NOT NULL FOREIGN KEY REFERENCES [SCHOOL]
([SchoolId]),
[ClassName] [varchar](50) NOT NULL,
[Description] [varchar](1000) NULL,
) GO
GetDatafrommultiple tablesinasingle
QueryusingJoins
Example:
select
SchoolName,
CourseName
from
YoulinkPrimaryKeysandForeignKeystogether
SCHOOL
innerjoinCOURSEonSCHOOL.SchoolId =COURSE.SchoolId
32
CreatingViews usingtheEditor
3
GraphicalInterfacewhereyoucanselectcolumns youneed
1
2
Add necessarytables
4
SavetheView
33
CreateView:
CreatingViews usingSQL
IF EXISTS (SELECT name
FROM
sysobjects
WHERE name = 'CourseData'
AND
type = 'V')
DROP VIEW CourseData
GO
CREATE VIEW CourseData
AS
SELECT
SCHOOL.SchoolId,
SCHOOL.SchoolName,
COURSE.CourseId,
COURSE.CourseName,
COURSE.Description
FROM
SCHOOL
INNER JOIN COURSE ON SCHOOL.SchoolId = COURSE.SchoolId
GO
UsingtheView:
select * from CourseData
AViewisa“virtual”tablethat
cancontaindatafrommultiple
tables
TheNameoftheView
InsidetheViewyoujointhe
different tablestogetherusing
theJOIN operator
YoucanUsetheViewasan
ordinary tableinQueries:
34
CreateStoredProcedure:
StoredProcedure
IFEXISTS (SELECT name
FROMsysobjects
WHEREname = 'StudentGrade'
AND
type= 'P')
DROPPROCEDUREStudentGrade
OG
CREATEPROCEDUREStudentGrade
@Studentvarchar(50),
@Coursevarchar(10),
@Gradevarchar(1)
AS
DECLARE
@StudentId int,
@CourseId int
AStoredProcedureislikeMethod inC#
- itisapieceofcodewithSQL
commandsthatdoaspecifictask– and
youreuseit
ProcedureName
InputArguments
Internal/LocalVariables
Note!Eachvariablestartswith@
selectStudentIdfromSTUDENTwhereStudentName =@Student
selectCourseId fromCOURSEwhereCourseName =@Course
insertintoGRADE(StudentId,CourseId,Grade)
values (@StudentId,@CourseId,@Grade)
GO
SQLCode(the“body”ofthe
StoredProcedure)
UsingtheStored Procedure:
execute StudentGrade 'John Wayne', 'SCE2006', 'B'
35
Trigger
ATriggerisexecutedwhenyouinsert,updateordeletedatainaTablespecifiedintheTrigger.
CreatetheTrigger:
IF EXISTS (SELECT name
FROM
sysobjects
WHERE name = 'CalcAvgGrade'
AND
type = 'TR')
DROP TRIGGER CalgAvgGrade
GO
CREATE TRIGGER CalcAvgGrade ON GRADE
FOR UPDATE, INSERT, DELETE
AS
DECLARE
@StudentId int,
@AvgGrade float
NameoftheTrigger
SpecifywhichTablethe
Triggershallworkon
Specifywhatkind ofoperationstheTrigger
shallacton
Internal/LocalVariables
select @StudentId = StudentId from INSERTED
select @AvgGrade = AVG(Grade) from GRADE where StudentId = @StudentId
update STUDENT set TotalGrade = @AvgGrade where StudentId = @StudentId
Insidethe
Triggeryoucan
useordinarySQL
statements,
createvariables,
etc.
SQLCode
(The“body”
oftheTrigger)
GO
Note!“INSERTED”isatemporarilytablecontainingthelatestinserteddata,anditisveryhandyto
useinsideatrigger
36
Exercise– SQL
• UseSQLqueriestoimplemntdataintoyour
LIBRARYdatabase
• WeTestthedifferentQueryTypes(CRUD):
INSERT,SELECT,UPDATEand DELETE
Summary
• DBMS – DatabaseManagementSystem
• SQL – StructuredQueryLanguage.ADatabase
ComputerLanguagedesignedforManagingDatain
RelationalDatabaseManagementSystems(RDBMS)
• ERDiagram– EntityRelationship.UsedforDesignand
ModelingofDatabases.SpecifyTablesandrelationship
betweenthem(PrimaryKeysandForeignKeys)
38
References
•
•
•
•
•
NTNU.(2013).TDT4140Systemutvikling.Available:
http://www.ntnu.no/studier/emner/TDT4140
UiO.(2013).INF1050- Systemutvikling.Available:
http://www.uio.no/studier/emner/matnat/ifi/INF1050/
O.Widder.(2013).geek&poke.Available:http://geek-and-poke.com
B.Lund.(2013).Lunch.Available:http://www.lunchstriper.no,
http://www.dagbladet.no/tegneserie/lunch/
S.Adams.Dilbert.Available:http://dilbert.com
39
Hans-PetterHalvorsen,M.Sc.
UniversityCollegeofSoutheastNorway
www.usn.no
E-mail:hans.p.halvorsen@hit.no
Blog:http://home.hit.no/~hansha/
Download