Upload
dodien
View
240
Download
1
Embed Size (px)
Citation preview
DatabaseLab
Hans-PetterHalvorsen
http://home.hit.no/~hansha/?lab=database
2017.03.24
MicrosoftSQLServerDatabase
DatabaseDesign&Modelling
SQLServerManagementStudio
LabOverview
CreateTables
DatabaseManagement
WewillcreateApplicationsinLabVIEW&VisualStudiothatWriteandReaddatatotheDatabase
NecessarySoftware
• ERwin (AcademicEdition,freedownloadfromInternet)• SQLServer(Express)Edition(DownloadforfreefromInternetor
MicrosoftImagine:“SQLServer2016ExpresswithServicePack1”)• LabVIEW(2016)• DAQmx DriverSoftware• LabVIEWSQLToolkit(©Hans-Petter Halvorsen)• VisualStudio(2016)
MakesuretoinstallthenecessarySoftwarebeforeyougotothelaboratory!
Software
Hardware
NIUSB-TC01ThermocoupleMeasurementDevice
YourPersonalComputer
Hardware
Note!Ifyoudon'thavetheTC-01deviceavailable,youmayusesomesimulatedvaluesinstead.
SystemOverviewDataLogging DataMonitoring
DAQ
Database
Trigger(s)
CalculateAverage,Max,MinTemperatureDataConvertTemperaturetoCelsius/Fahrenheit
StoredProcedure(s)
Viewsand/orStoredProcedure(s)
DAQmxDriver
Tables
LoggingApp
MonitoringApp
Views
StoresProcedures
Triggers
TemperatureSensor
TC-01Thermocouple
TableDesign
Network
SystemOverview
LabAssignmentOverview1. DesignDatabaseusingERwin.2. ImplementTables,Views,Stored
ProceduresandTriggersusingSQLServer.3. CreateaDataloggingAppusingLabVIEW.4. CreateaDataMonitoringAppusingVisual
Studio/C#.Seenextslidesfordetails...
LabAssignment• Makesuretoreadthewholeassignmentbeforeyoustarttosolveanyoftheproblems.
• Ifyoumissassumptionsforsolvingsomeoftheproblems,youmaydefineproperassumptionsyourself.
• TheTasksaresomewhatlooselydefinedandmorelikeguidelines,sofeelfreetointerprettheTasksinyourownway.
• FeelfreetoExplore!– AddValuetoyourApplications!
TheTeacherdonthavealltheanswers(veryfewactuallyL)!!Sometimesyoujustneedto“Google”inordertosolveyourproblems,CollaboratewithotherStudents,etc.ThatshowyouLearn!
TheteacherhavenotdonealltheTasksindetail,sohemaynothavealltheanswers!That'showitisinreallifealso!
Veryoftenitworksononecomputerbutnotonanother.Youmayhaveotherversionsofthesoftware,youmayhaveinstalleditinthewrongorder,etc...InthesecasesGoogleisyourbestfriend!
MySystemisnot
Working??
YouprobablywillfindtheanswerontheInternet
Checkyourelectriccircuit,electricalcables,DAQdevice,etc.Checkifthewiresfrom/totheDAQdeviceiscorrect.AreyouusingthesameI/OChannelinyourSoftwareasthewiringsuggest?etc.
Troubleshooting&Debugging
Anotherpersonintheworldprobablyhadasimilarproblem
UsetheDebuggingToolsinyourProgrammingIDE.VisualStudio,LabVIEW,etc.havegreatDebuggingTools!Usethem!!
VisualStudio UseavailableResourcessuchasUserGuides,Datasheets,TextBooks,Tutorials,Examples,Tips&Tricks,etc.
Yourhardwaredevicemostlikelyworks,soyoudon'tneedanewdevice!StillnotworkingafterTroubleshooting&Debugging?Filloutan“EquipmentErrorForm”
“GoogleIt”!
ERwin
Hans-PetterHalvorsen,M.Sc.
DatabaseModellingandDesign
Task1
ERwinAcademicEdition• DatabaseModellingTool forcreatingER(EntityRelationship)diagrams
• Itsfree,butyouneedtoapplyforit- soitmaytake2-5daysbeforeyougetit!
• http://erwin.com/education/erwin-academic-program/academic-edition/
DatabaseDesign– ERDiagramERDiagram(Entity-RelationshipDiagram)• UsedforDesignandModelingofDatabases.• SpecifyTablesandrelationship betweenthem(PrimaryKeysandForeignKeys)
PrimaryKey PrimaryKey ForeignKey
TableName
TableName
RelationalDatabase.InarelationaldatabaseallthetableshaveoneormorerelationwitheachotherusingPrimaryKeys(PK)andForeignKeys(FK).Note!YoucanonlyhaveonePKinatable,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”,...)
Itisrecommendedthatyoufollowtheseguidelines!
DatabaseSystem• CreatetheoverallSpecificationsandDesignforyourSystem
• StartbyDesigntheDatabaseTablesusingERwinandcreateaSQLScript
• ImplementtheTablesinSQLServer,e.g.,usingaSQLScriptgeneratedinERwin
• ThenCreatenecessaryViews,StoredProceduresandTriggerswithintheSQLServerManagementStudio.ItisrecommendedthatyousavetheseasSQLFiles
Congratulations!- YouarefinishedwiththeTask
SQLServer
Hans-PetterHalvorsen,M.Sc.
DatabaseImplementationandStructuredQueryLanguage(SQL)
Task2
SQLServer
DatabaseEngineandRepositoryManagementStudio
Notetheseare2separatemodulesyouneedtoinstall
AgraphicalinterfacetotheDatabaseEnginewhereyoucancreatetablesandmanipulatedata,etc.
TheDataStorage
SQLServer• StartbyDesigntheDatabaseTablesusingERwinandcreateaSQLScript
• ImplementtheTablesinSQLServer,e.g.,usingaSQLScriptgeneratedinERwin
• CreatenecessaryViews,StoredProceduresandTriggerswithintheSQLServerManagementStudio.– ItisrecommendedthatyouwaittocreatethemuntilyouneedthemintheLabVIEWorC#Code
MicrosoftSQLServerManagementStudio
WriteyourQueryhere
TheresultfromyourQuery
YourDatabase
YourTables
YourSQLServer
Software
2
3
4
5
1
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
Views,StoredProceduresandTriggers• Views:Viewsarevirtualtablesforeasieraccesstodatastoredinmultipletables.
• StoredProcedures:AStoredProcedureisaprecompiledcollectionofSQLstatements.Inastoredprocedureyoucanuseifsentence,declarevariables,etc.
• Triggers:Adatabasetriggeriscodethatisautomaticallyexecutedinresponsetocertaineventsonaparticulartableinadatabase.
DatabaseViews
• ADatabaseViewisa“virtual”tablethatcancontaindatafrommultipletables
• YouprobablyneedtoCreateandUseoneormoreDatabaseViewsinordertogetDatafromtheDatabase,bothintheDataLoggingAppandDataMonitoringApp
ItisrecommendedthatyouwaittocreatethemuntilyouneedthemintheLabVIEWorC#Code
ViewsIF 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
YoucanUsetheViewasanordinarytableinQueries:
AViewisa“virtual”tablethatcancontaindatafrommultiple tables
InsidetheViewyoujointhedifferenttablestogetherusingtheJOIN operator
TheNameoftheView
CreateView:
UsingtheView:
Thispartisnotnecessary– butifyoumakeanychanges,youneedtodeletetheoldversionbeforeyoucanupdateit
select * from CourseData
1
2
ViewTemplateIF EXISTS (SELECT name
FROM sysobjectsWHERE name = '<ViewName>' AND type = 'V')
DROP VIEW <ViewName>GO
CREATE VIEW <ViewName>AS
SELECT<TableName>.<ColumnName>,<TableName>.<ColumnName>,<TableName>.<ColumnName>,<TableName>.<ColumnName>,<TableName>.<ColumnName>
FROM<TableName1>INNER JOIN <TableName2> ON <TableName1>.<PrimKeyColumnName1> = <TableName2>.<PrimKeyColumnName2>GO
CopytoSQLServerManagementStudio,saveasaSQLFile(.sql)asthesamenameastheViewyouaregoingtocreate.Storeallyourfilesonyourharddrive.
StoredProceduresTypicallyyouneedsomeStoredProcedures:• TheDataloggingAppshoulduseaStoredProcedureinordertosaveMeasurementDatatotheDatabase.
• TheDataloggingAppshoulduseaStoredProcedureinordertosaveConfigurationDatatotheDatabase.– LoggingInterval– Unit(CelsiusorFahrenheit)
ItisrecommendedthatyouwaittocreatethemuntilyouneedthemintheLabVIEWorC#Code
StoredProceduresIFEXISTS(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
1
2
StoredProcedureTemplateIF EXISTS (SELECT name
FROM sysobjectsWHERE name = '<StoredProcedureName>' AND type = 'P')
DROP PROCEDURE <StoredProcedureName>GO
CREATE PROCEDURE <StoredProcedureName>@<InputVariable1> <DataType>,@<InputVariable2> <DataType>AS
DECLARE@<InternalVariable1> <DataType>,@<InternalVariable2> <DataType>
select @<InternalVariable1> = <ColumnName> from <TableName> where <ColumnName> = @<InputVariable1>
insert into <TableName> (<ColumnName1>, <ColumnName2>, ...) values (@<InternalVariable1>, @<Inputvariable1>, ...)GO
CopytoSQLServerManagementStudio,saveasaSQLFile(.sql)asthesamenameastheSPyouaregoingtocreate.Storeallyourfilesonyourharddrive.
DatabaseTrigger(s)YoumayneedoneormoreTriggersthatdoe.g.thefollowing:• ConvertTemperaturetoCelsius/Fahrenheit
– E.g.,IfUnit=Celsius,theTriggershouldConvertTemperatureDatatoFahrenheit
– E.g.,IfUnit=Fahrenheit,theTriggershouldConvertTemperatureDatatoCelsius
– BothCelsiusandFahrenheitvaluesshouldprobablybestoredintheDatabaseforeasyaccesslaterinMonitoringApp
• CalculateAverage,Max,MinTemperatureData– TheTriggershouldcalculateandstoreAverage(Mean),MaxandMin
TemperatureDataintotheDatabase
YoumaywaittocreatethemuntilyouneedthemintheLabVIEWorC#Code
TriggersIF 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,updateordeletedatainaTablespecifiedintheTrigger.
InsidetheTriggeryoucanuseordinarySQLstatements,createvariables,etc.
NameoftheTrigger
SpecifywhichTabletheTriggershallworkon
Internal/LocalVariables
SQLCode(The“body”oftheTrigger)
SpecifywhatkindofoperationstheTriggershallacton
Note!“INSERTED”isatemporarilytablecontainingthelatestinserteddata,anditisveryhandytouseinsideatrigger
TriggerExample:
Thispartisnotnecessary– butifyoumakeanychanges,youneedtodeletetheoldversionbeforeyoucanupdateit
TriggerTemplateIF EXISTS (SELECT name
FROM sysobjectsWHERE name = '<TriggerName>' AND type = 'TR')
DROP PROCEDURE <TriggerName>GO
CREATE TRIGGER <TriggerName>FOR UPDATE, INSERT, DELETE –-Delete the ones not neededAS
DECLARE@<InternalVariable1> <DataType>,@<InternalVariable2> <DataType>
select @Variable1 = Column1 from INSERTEDselect @Variable2 = AVG(Column2) from TABLE where Column1 = @Variable1update TABLE set Column3= @Variabl2e where Column1= @Variable1
GO
CopytoSQLServerManagementStudio,saveasaSQLFile(.sql)asthesamenameastheTriggeryouaregoingtocreate.Storeallyourfilesonyourharddrive.
Congratulations!- YouarefinishedwiththeTask
DataloggingusingLabVIEW
Hans-PetterHalvorsen,M.Sc.Task3
DataloggingusingLabVIEW
MicrosoftSQLServerDatabase
DatabaseDesign&Modelling
TC-01Thermocouple
StoredProcedure(s)DAQ
Triggers
CalculateAverage,Max,MinTemperatureData
ConvertTemperaturetoCelsius/Fahrenheit
StartbyDesignandImplementtheDatabaseTablesusingERwin
CreateStoredProcedure(s)andTriggersinSQLServer
Data
LabVIEWHMIExample
TemperatureData:30
Exit
0
DataloggingApp
℃
TheTemperatureDatafromtheTC-01DAQdeviceshouldbestoredintheDatabase.
ShowTemperatureinCelsiusorFahrenheitdependingontheConfiguration
Chart Configuration
ThisisjustaDesignSketch!FeelfreetoExplore!
TabControl
Chart
Button
Time
LabVIEWHMIExample
Exit
DataloggingApp
TheTemperatureDatafromtheTC-01DAQdeviceshouldbestoredintheDatabase.
Chart Configuration
2LoggingInterval:
sec.
CelsiusUnit:
Save
TabControl
E.g.,IfUnit=Celsius,theTriggershouldConvertTemperatureDatatoFahrenheit
E.g.,IfUnit=Fahrenheit,theTriggershouldConvertTemperatureDatatoCelsius
NumericControl
ComboBox
Buttons
ThisisjustaDesignSketch!FeelfreetoExplore!
UseaStoredProcedureinordertoSaveDatatotheDatabase
LabVIEWSQLToolkit
http://home.hit.no/~hansha/documents/labview/code/SQLToolkit.zip
ForEasyDatabaseCommunicationwithLabVIEW
©Hans-PetterHalvorsenDownloadforfreehere:
SoftwareSoftware
LabVIEWSQLToolkitExamples
38
Example1:GetDatafromDatabaseintoLabVIEW:
Example2:WriteDatatoDatabasefromLabVIEW:
EasyAccesstoDatabaseSystemsfromLabVIEW
YourODBCConnection
2DTablewithData
1
Query
Query
2 3
1 2 3
TrytheseExamples
ConnecttoDatabase• Alt1:UseODBC– SetupyourDatabaseconnectionusingaWizard(“ODBCDataSourceAdministrator”)
• Alt2:UseConnectionStringdirectly– Alt2.1:WindowsAuthentication:
DataSource=<dbserver>;InitialCatalog=<dbname>;Trusted_Connection=True
– Alt2.2:SQLServerAuthentication:DataSource=<dbserver>;InitialCatalog=<dbname>;PersistSecurityInfo=True;User ID=sa;Password=<password>
SeeExamplesonnextslides...
ODBCODBC(OpenDatabaseConnectivity)isastandardizedinterface(API)foraccessingthedatabasefromaclient.Youcanusethisstandardtocommunicatewithdatabasesfromdifferentvendors,suchasOracle,SQLServer,etc.ThedesignersofODBCaimedtomakeitindependentofprogramminglanguages,databasesystems,andoperatingsystems.ControlPanel→AdministrativeTools→DataSources(ODBC)
WewillusethisODBCConnectionlaterinLabVIEWinordertoopentheDatabaseConnectionfromLabVIEW
Theory
Note!Makesuretousethe32bit versionoftheODBCTool!
ODBC– StepbyStepInstructions
41
TheNameofyourSQLServer
TheNameofyourODBCConnection
UseeitherWindowsorSQLServerauthentication(Windowsissimplesttouse!)
SelecttheDatabaseyouareusing
Testyourconnectiontoseeifitsworks
LabVIEWSQLToolkitExampleEasyAccesstoDatabaseSystemsfromLabVIEW
AlternativeSolution:TypeintheConnectionStringforyourDatabase
Note!Whenusingthismethod,youdontneedtocreateanODBCConnectionfirst!
YourPasswordforthesauser
YourSQLServerInstance
TypeyourDatabasehere
YourSQLQuery
LabVIEWSQLToolkitExample
43
YoushoulduseaStoredProcedure
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-pointNumber.
ResultingSQLQuery:
GUI/HMI
Code:2
1
3
Congratulations!- YouarefinishedwiththeTask
DataMonitoringusingVisualStudio/C#
Hans-PetterHalvorsen,M.Sc.Task4
DataMonitoringusingVisualStudio/C#
MicrosoftSQLServerDatabase
StoredProcedure(s)View(s)
YoucancreateaDesktopApplication(WinForm ApporWPFApp)oraWebApplication(WebForm App)
VisualStudioHMIExample
Date&Time Value[C] Value[F]2016.03.2214:45 22 71.6
... ... ...
... ... ...
... ... ...
TemperatureData:
0
30
DataMonitoringApp
Average:
Min:
Max:
22
10
26
℃
℃
℃
YoushouldgettheDatafromtheDatabase
℃
TextBoxesLabels
DataGridView
Chart
ThisisjustaDesignSketch!FeelfreetoExplore!
TypicallyyougetDatafromtheDatabaseusingViewsand/orStoredProcedures
Time
49
using System.Configuration;
...
public partial class BookList : System.Web.UI.Page{private string connectionString = ConfigurationManager.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;}
}
InthisexampletheConnectionStringtotheDatabaseisstoredinthe“App.config”file
VisualStudio/C#DatabaseExample
<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>
Note!YouneedtoaddaReferenceinordertousetheConfigurationManager
ConfigurationManagerNote!YouneedtoaddaReferencein
ordertousetheConfigurationManagerRight-click
51
VisualStudio/C#DatabaseExampleusing 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;}
}
ThisisaDatabaseView
Timer
publicForm1(){InitializeComponent();
timer1.Start();}
privatevoidtimer1_Tick(objectsender,EventArgs e){…//ReadfromDB…//Formatting…//PlotData
}
TimerEvent:
Initialization:
Properties:
StructureyourCodeproperly!!DefineClassesandMethodswhichyoucanusehere
InVisualStudioyoumaywanttouseaTimerinsteadofaWhileLoopinordertoreadvaluesatspecificintervals.
YoumayspecifytheTimerIntervalinthePropertiesWindow
Selectthe“Timer”componentintheToolbox
Double-clickontheTimerobjectinordertocreatetheEvent
2
3
4
1
ChartinginVisualStudiohttps://msdn.microsoft.com/en-us/library/dd489237.aspxVisualStudiohasaChartcontrolthatyoucanuseinWindowsFormsorWebapplication(ASP.NET)
http://www.i-programmer.info/programming/uiux/2756-getting-started-with-net-charts.html
using System.Windows.Forms.DataVisualization.Charting;...chart1.Series.Clear();chart1.Series.Add("My Data");chart1.Series["My Data"].ChartType=SeriesChartType.Line;...int[] x = {1, 2, 3, 4, 5, 6, 7, 8};int[] y = {20, 22, 25, 24, 28, 27, 24, 26};for (int i = 0; i < x.Length; i++){
chart1.Series["My Data"].Points.AddXY(x[i],y[i]);}
CreatingaWebApp?UsethefollowingNamespaceinstead:System.Web.UI.DataVisualization.Charting
Congratulations!- YouarefinishedwiththeTask
Tables
LoggingApp
MonitoringApp
Views
StoresProcedures
Triggers
TemperatureSensor
TC-01Thermocouple
TableDesign
Network
FinishedSolution
Congratulations!- Youarefinishedwithall theTasksintheAssignment!
Hans-PetterHalvorsen,M.Sc.
UniversityCollegeofSoutheastNorwaywww.usn.no
E-mail:[email protected]:http://home.hit.no/~hansha/