Database Lab
Database Lab
Database Lab
24
Database Lab
http://home.hit.no/~hansha/?lab=database
Hans-Petter Halvorsen
Lab Overview
Database Design
& Modelling Create Tables
SQL Server Management Studio
Microsoft
Database Management SQL Server
Database
Make sure to install the necessary Software before you go to the laboratory!
Hardware
Hardware
DAQmx Driver
Trigger(s)
DAQ Convert Temperature to Celsius/Fahrenheit
Calculate Average, Max, Min Temperature Data
System Overview
Logging Network Monitoring
App App
Temperature
Sensor Triggers
Views
Tables
Table Design
Lab Assignment Overview
1. Design Database using ERwin.
2. Implement Tables, Views, Stored
Procedures and Triggers using SQL Server.
3. Create a Datalogging App using LabVIEW.
4. Create a Data Monitoring App using Visual
Studio/C#.
See next slides for details...
Lab Assignment
Make sure to read the whole assignment before you
start to solve any of the problems.
If you miss assumptions for solving some of the
problems, you may define proper assumptions
yourself.
The Tasks are somewhat loosely defined and more
like guidelines, so feel free to interpret the Tasks in
your own way.
Feel free to Explore! Add Value to your
Applications!
The teacher have not done Very often it works on one computer but
not on another. You may have other
all the Tasks in detail, so he versions of the software, you may have
may not have all the installed it in the wrong order, etc...
answers! That's how it is in In these cases Google is your best friend!
real life also!
The Teacher dont have all the answers (very few actually L)!! Sometimes you just need to Google in
order to solve your problems, Collaborate with other Students, etc. Thats how you Learn!
Troubleshooting & Debugging
Visual Studio Use available Resources
Use the Debugging Tools in your such as User Guides,
Programming IDE. Datasheets, Text Books,
Visual Studio, LabVIEW, etc. have great Tutorials, Examples,
Debugging Tools! Use them!! Tips & Tricks, etc.
My System
is not
Working??
Google It!
Your hardware device most likely works, so
You probably will find the you don't need a new device! Still not working
answer on the Internet after Troubleshooting & Debugging? Fill out
an Equipment Error Form
Check your electric circuit, electrical cables, DAQ device, etc. Check if
Another person in the world probably the wires from/to the DAQ device is correct. Are you using the same
had a similar problem I/O Channel in your Software as the wiring suggest? etc.
ERwin
Database Modelling and Design
Column
Names
Management Studio
Database Engine and Repository
Your
Tables
SELECT
<TableName>.<ColumnName>,
<TableName>.<ColumnName>,
<TableName>.<ColumnName>,
<TableName>.<ColumnName>,
<TableName>.<ColumnName>
FROM
<TableName1>
INNER JOIN <TableName2> ON <TableName1>.<PrimKeyColumnName1> = <TableName2>.<PrimKeyColumnName2>
GO
Stored Procedures
Typically you need some Stored Procedures:
The Datalogging App should use a Stored Procedure in
order to save Measurement Data to the Database.
The Datalogging App should use a Stored Procedure in
order to save Configuration Data to the Database.
Logging Interval
Unit (Celsius or Fahrenheit)
It is recommended that you wait to create them until you
need them in the LabVIEW or C# Code
1
Create Stored Procedure: Stored Procedures
IF EXISTS (SELECT name
FROM sysobjects
WHERE name = 'StudentGrade'
A Stored Procedure is like a Method in C# - it
AND type = 'P')
DROP PROCEDURE StudentGrade
is a piece of code with SQL commands that
OG do a specific task and you reuse it
CREATE PROCEDURE StudentGrade This part is not necessary but if you make any
@Student varchar(50), changes, you need to delete the old version before
@Course varchar(10), you can update it
@Grade varchar(1)
Procedure Name
AS
Input Arguments
DECLARE
@StudentId int, Internal/Local Variables
@CourseId int Note! Each variable starts with @
select @StudentId = StudentId from STUDENT where StudentName = @Student
DECLARE
@<InternalVariable1> <DataType>,
@<InternalVariable2> <DataType>
You may wait to create them until you need them in the LabVIEW or C# Code
A Trigger is executed when you insert, update or delete data in a Table
specified in the Trigger. Trigger Example:
Triggers
IF EXISTS (SELECT name
FROM sysobjects
WHERE name = 'CalcAvgGrade' This part is not necessary but if you make any
AND type = 'TR') changes, you need to delete the old version before
DROP TRIGGER CalgAvgGrade you can update it
GO
Name of the Trigger Inside the
CREATE TRIGGER CalcAvgGrade ON GRADE Trigger you can
FOR UPDATE, INSERT, DELETE
AS
Specify which Table the use ordinary SQL
Trigger shall work on statements,
DECLARE
@StudentId int, Specify what kind of operations the Trigger create variables,
@AvgGrade float shall act on etc.
Internal/Local Variables
select @StudentId = StudentId from INSERTED
SQL Code
select @AvgGrade = AVG(Grade) from GRADE where StudentId = @StudentId (The body
update STUDENT set TotalGrade = @AvgGrade where StudentId = @StudentId of the Trigger)
GO
Note! INSERTED is a temporarily table containing the latest inserted data, and it is very handy to use inside a trigger
Trigger Template
Copy to SQL Server Management Studio, save as a SQL
File (.sql) as the same name as the Trigger you are going
to create. Store all your files on your hard drive.
IF EXISTS (SELECT name
FROM sysobjects
WHERE name = '<TriggerName>'
AND type = 'TR')
DROP PROCEDURE <TriggerName>
GO
DECLARE
@<InternalVariable1> <DataType>,
@<InternalVariable2> <DataType>
GO
Congratulations! - You are finished with the Task
Datalogging using LabVIEW
TC-01 Thermocouple
Data Microsoft
SQL Server
DAQ Stored Procedure(s)
Database
Triggers
Convert Temperature to Celsius/Fahrenheit
Calculate Average, Max, Min Temperature Data
LabVIEW HMI Example
The Temperature Data from the TC-01 DAQ device should be stored in the Database.
Datalogging App This is just a Design Sketch!
Feel free to Explore!
Tab Control Chart Configuration
Temperature Data:
30
Show Temperature in
Celsius or Fahrenheit
depending on the
Configuration
Chart
0
Time
Button Exit
LabVIEW HMI Example
The Temperature Data from the TC-01 DAQ device should be stored in the Database.
Datalogging App This is just a Design Sketch!
Feel free to Explore!
Tab Control Chart Configuration
Hans-Petter Halvorsen
Download for free here:
http://home.hit.no/~hansha/documents/labview/code/SQLToolkit.zip
LabVIEW SQL Toolkit Examples
Easy Access to Database Systems from LabVIEW
Example 1: Get Data from Database into LabVIEW: 2D Table with Data
1 2 3
Query
Your ODBC
Connection Try these Examples
Example 2: Write Data to Database from LabVIEW:
1 2 3
Query
38
Connect to Database
Alt 1: Use ODBC
Setup your Database connection using a Wizard (ODBC
Data Source Administrator)
Alt 2: Use Connection String directly
Alt 2.1: Windows Authentication:
Data Source=<dbserver>;Initial Catalog=<dbname>;Trusted_Connection=True
Alt 2.2: SQL Server Authentication:
Data Source=<dbserver>;Initial Catalog=<dbname>;Persist Security Info=True;User ID=sa;Password=<password>
See Examples on next slides...
ODBC Theory
ODBC (Open Database Connectivity) is a standardized interface (API) for accessing
the database from a client. You can use this standard to communicate with
databases from different vendors, such as Oracle, SQL Server, etc. The designers
of ODBC aimed to make it independent of programming languages, database
systems, and operating systems.
Control Panel Administrative Tools Data Sources (ODBC)
We will use this ODBC Connection later
in LabVIEW in order to open the
Database Connection from LabVIEW
Note! When using this method, you dont need to create an ODBC Connection first!
LabVIEW SQL Toolkit Example
43
LabVIEW SQL Toolkit Example
1 GUI/HMI If we want to save input data from the user
we can use the Format Into String function
The %s operator will be replaced by the text
from the TextBox on the Front Panel. For
Numbers we can use %d (Integer) or %f for
Floating-point Number.
2 Code:
Microsoft
SQL Server
Database View(s)
Stored Procedure(s)
...
}
}
In this example the Connection
String to the Database is stored in
private void FillBookGrid()
{ the App.config file
List<Book> bookList = new List<Book>();
Book book = new Book(); <connectionStrings>
<add name="LibraryDBConnectionString"
bookList = book.GetBooks(connectionString); connectionString="Data Source=macwin8;Initial
Catalog=BOOKS;Persist Security Info=True;User
ID=sa;Password=xxx"
gridBookList.DataSource = bookList;
providerName="System.Data.SqlClient" />
} </connectionStrings>
}
49
Configuration Manager
Note! You need to add a Reference in
order to use the Configuration Manager
Right-click
Visual Studio/C# Database Example
using System.Data.SqlClient;
using System.Data.SqlTypes;
using System.Data;
string selectSQL = "select BookId, Title, Isbn, PublisherName, AuthorName, CategoryName from GetBookData";
con.Open();
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;
51
}
}
1
Timer In Visual Studio you may want to use a Timer instead of a While Loop in
order to read values at specific intervals.
Select the Timer component in the Properties: 3
2 Initialization: Toolbox
public Form1()
{
InitializeComponent();
You may specify the Timer Interval
timer1.Start(); in the Properties Window
} Double-click on the Timer object in
Timer Event: order to create the Event
4
private void timer1_Tick(object sender, EventArgs e) Structure your Code
properly!!
{
Define Classes and Methods
//Read from DB which you can use here
//Formatting
//Plot Data
}
Charting in Visual Studio
Visual Studio has a Chart control that you can use in Windows Forms or Web application (ASP.NET)
https://msdn.microsoft.com/en-us/library/dd489237.aspx
http://www.i-programmer.info/programming/uiux/2756-getting-started-with-net-charts.html
using System.Windows.Forms.DataVisualization.Charting;
...
Creating a Web App? Use the following Namespace instead:
chart1.Series.Clear(); System.Web.UI.DataVisualization.Charting
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]);
}
Congratulations! - You are finished with the Task
Finished Solution
Logging Network Monitoring
App App
Temperature
Sensor Triggers
Views
Tables
Table Design
Congratulations! - You are finished with all the Tasks in the Assignment!
Hans-Petter Halvorsen, M.Sc.
E-mail: [email protected]
Blog: http://home.hit.no/~hansha/