Sie sind auf Seite 1von 114

CL-213

Fundamentals of Database Systems


LAB MANUAL

DEPARTMENT OF ELECTRICAL ENGINEERING,


FAST-NU, LAHORE
Lab Manual of Fundamentals of Database Systems

Created by: Ms. ShaziaHaque

Date: 10thJuly, 2014

Last Updated by: Ms. ShaziaHaque

Date: August, 2019

Approved by the HoD: Dr. S.M.Sajid

Date: August, 2016

Page | 2
Lab Manual of Fundamentals of Database Systems

Table of Contents
Sr. No. Description Page No.

1 List of Equipment 04

2 Experiment No. 01, Introduction to HTML 05

3 Experiment No. 02, Cascading Style Sheets and JavaScript 11

4 Experiment No. 03, Introduction to SQL Server 2008 DBMS 17

5 Experiment No. 04, Introduction to SQL and DDL 26

6 Experiment No. 05, Introduction to SQL DML 31

7 Experiment No. 06, Advanced SQL 36

8 Experiment No. 07, Views and Stored procedures 39

9 Experiment No. 08, Triggers 45

10 Experiment No. 09, Introduction to Erwin Data Modeling tool 50

Experiment No. 10, Building ASP.net web applications with Database


11 64
Connectivity
Experiment No. 11, ASP.net GridView Control – Deletion and
12 86
updation/insertion
Experiment No. 12, ASP.net Passing values across webpages and SQL
13 100
Injection

14 Appendix A, Lab Evaluation Criteria 109

15 Appendix B, Safety around Electricity 110

16 Appendix C, Guidelines on preparing Lab Reports 112

Page | 3
Lab Manual of Fundamentals of Database Systems

List of Equipment
Sr. No. Description

1 Workstations (PCs)

2 Visual Studio 2012C# (software)

3 Erwin data modeling tool (software)

4 Microsoft SQL Server 2014 (software)

Page | 4
Lab Manual of Fundamentals of Database Systems

EXPERIMENT 1
INTRODUCTION TO HTML
Objective

• Introduction to HTML language.

HTML is a language for describing web pages.

• HTML stands for Hyper Text Markup Language


• HTML is not a programming language, it is a markup language
• A markup language is a set of markup tags
• The purpose of the tags are to describe page content

HTML Tags

HTML markup tags are usually called HTML tags

• HTML tags are keywords (tag names) surrounded by angle brackets like <html>
• HTML tags normally come in pairs like <b> and </b>
• The first tag in a pair is the start tag, the second tag is the end tag
• The end tag is written like the start tag, with a forward slash before the tag name
• Start and end tags are also called opening tags and closing tags

Web Browsers

The purpose of a web browser (Chrome, Internet Explorer, and Firefox) is to read HTML
documents and display them as web pages. The browser does not display the HTML tags, but
uses the tags to interpret the content of the page. A basic HTML page structure is shown in
Figure 1 below.

Page | 5
Lab Manual of Fundamentals of Database Systems

Figure1

HTML Element

• An HTML element starts with a start tag / opening tag


• An HTML element ends with an end tag / closing tag
• The element content is everything between the start and the end tag
• Some HTML elements have empty content
• Empty elements are closed in the start tag
• Most HTML elements can have attributes

HTML Headings
<h1>Check this out</h1>
<h2>What you think of it now</h2>
<h3>And what about now</h3>

HTML Paragraphs
<p>This is a paragraph.</p>
<p>This is another paragraph.</p>
Use the <br /> tag if you want a line break (a new line) without starting a new paragraph

Some other HTML formatting tags are given in Figure 2 below.

Page | 6
Lab Manual of Fundamentals of Database Systems

Figure 2

HTML Lists
An unordered list starts with the <ul> tag. Each list item starts with the <li> tag.
The list items are marked with bullets (typically small black circles).

<ul>
<li>EE</li>
<li>CS</li>
<li>BBA</li>
</ul>

HTML Images

<imgsrc="temp.jpg" width="250" height="142" />


<imgsrc="cloud.jpg" alt="Cloud" />

To display an image on a page, you need to use the src attribute. Src stands for "source". The
value of the src attribute is the URL of the image you want to display. The height and width
attributes are used to specify the height and width of an image.

The URL points to the location where the image is stored. An image named "boat.gif",
located in the "images" directory on "www.google.com" has the URL:
http://www.google.com/images/boat.gif.

HTML Links

A hyperlink (or link) is a word, group of words, or image that you can click on to jump to a
new document or a new section within the current document. When you move the cursor
over a link in a Web page, the arrow will turn into a little hand.
Links are specified in HTML using the <a> tag.
The <a> tag can be used in two ways:

1. To create a link to another document, by using the href attribute


Page | 7
Lab Manual of Fundamentals of Database Systems

2. To create a bookmark inside a document, by using the name attribute

<a href="http://www.google.com">This is a link</a>


<a href="http://www.google.com/" target="_blank">Google Karo</a>

The target attribute specifies where to open the linked document.


The name attribute specifies the name of an anchor.
The name attribute is used to create a bookmark inside an HTML document.

Using Images as HTML Links

To use an image as a link, you will have to use two things you have already learned.
1. How to create a link.
2. How to add an image to the page.

<a href="http://www.google.com">
<imgsrc="sunset.jpg">
</a>

Linking Within a Single Page

Maybe you would like to give someone a way back to the top of the page when they are at
the bottom. Or maybe you want to divide it into sections and use a table of contents at the
top. Well, the way to do this is to use a named anchor, which is a specific area of your page
you want to make a link to. You could link to any part of the page, but for now, let's say you
want to create a link to the top of your page. To do this, go to the top of the body section
(right after the body tag). Now type the following tag:

<a name="top"></a>

You can place any name you wish inside the quotes. This just makes it easy to see where we
are going to end up. Now, go anywhere between the body tags and type this link:

<a href="#top">Back to the Top</a>

If you click on this link, you will be sent back to the top of the page.

HTML Tables

Tables are defined with the <table> tag.

A table is divided into rows (with the <tr> tag), and each row is divided into data cells (with the
<td> tag). td stands for "table data," and holds the content of a data cell. A <td> tag can contain
text, links, images, lists, forms, other tables, etc.

If you do not specify a border attribute, the table will be displayed without borders. Sometimes
this can be useful, but most of the time, we want the borders to show.

Page | 8
Lab Manual of Fundamentals of Database Systems

Header information in a table are defined with the <th> tag.

<table border="1">
<tr>
<th>Department</th>
<th>Course</th>
</tr>
<tr>
<td>CS</td>
<td>Data Structure</td>
</tr>
<tr>
<td>EE</td>
<td>Circuit Analysis</td>
</tr>
</table>

INPUT Control

a. Input(Text)
<input id="Text1" type="text" value="Please Enter City" />

b. Input(Password)
<input id="Password1" type="password" value="dummy" />

c. Input(Checkbox)
<input id="Checkbox1" type="checkbox" checked="true" />

d. Input(Radio)
<input id="Radio1" type="radio" checked="true" />

e. Input(Button)
<input id="Button1" type="button" value="button" />

Page | 9
Lab Manual of Fundamentals of Database Systems

Exercise 1: Create a first page “firstpage.html” as shown in Figure3 below

Figure 3

Good Reference:

http://www.w3schools.com

Post Lab Questions


1. Design a webpage for a sports website using HTML only. Use your imagination and be
innovative. For help explore w3schools.
2. Find and list the differences between HTML version 3 and HTML version 5.

Page | 10
Lab Manual of Fundamentals of Database Systems

EXPERIMENT 2
Cascading Style Sheets and JavaScript

Objective
• Introduction to CSS (Cascading Style sheets)
• Apply CSS to your html page
• Client side validation and learn how to apply client validation using JavaScript

At the end of this lab you will be able to

• Create CSS style sheet and Apply CSS


• Create and use JavaScript functions
• Apply Client side validations

What is CSS?
CSS stands for Cascading Style Sheets
Styles define how to display HTML elements
Styles were added to HTML 4.0 to solve a problem
External Style Sheets can save a lot of work
External Style Sheets are stored in CSS files

Why we needed CSS?


HTML was never intended to contain tags for formatting a document.HTML was intended to define
the content of a document, like:
<h1>This is a heading</h1>
<p>This is a paragraph.</p>
When tags like <font>, and color attributes were added to the HTML 3.2 specification, it started a
nightmare for web developers. Development of large web sites, where fonts and color information
were added to every single page, became a long and expensive process.
To solve this problem, the World Wide Web Consortium (W3C) created CSS.
CSS defines HOW HTML elements are to be displayed.
Styles are normally saved in external .css files. External style sheets enable you to change the
appearance and layout of all the pages in a Web site, just by editing one single file!

CSS Syntax
A CSS rule has two main parts: a selector, and one or more declarations as shown in Figure 1:

Figure1

Page | 11
Lab Manual of Fundamentals of Database Systems

The selector is normally the HTML element you want to style.


Each declaration consists of a property and a value.
The property is the style attribute you want to change. Each property has a value.

In addition to setting a style for a HTML element, CSS allows you to specify your own selectors
called "id" and "class".
Id Selector Syntax
The id selector is used to specify a style for a single, unique element.
The id selector uses the id attribute of the HTML element, and is defined with a "#".
The style rule below will be applied to the element with id="para1":

#para1
{
text-align:center;
color:red;
}

Class Selector Syntax


The class selector is used to specify a style for a group of elements. Unlike the id selector, the class
selector is most often used on several elements.
This allows you to set a particular style for many HTML elements with the same class. The class
selector uses the HTML class attribute, and is defined with a "."
In the example below, all HTML elements with class="center" will be center-aligned:

.center {text-align:center;}

How to apply CSS


There are three ways of inserting a style sheet:
• External style sheet
• Internal style sheet
• Inline style

External Style sheet


An external style sheet is ideal when the style is applied to many pages. With an external style sheet,
you can change the look of an entire Web site by changing one file. Each page must link to the style
sheet using the <link> tag. The <link> tag goes inside the head section:

<head>
<link rel="stylesheet" type="text/css" href="mystyle.css"/>
</head>

An external style sheet can be written in any text editor. The file should not contain any html tags.
Your style sheet should be saved with a .css extension. An example of a style sheet file is shown
below:

hr {color:sienna;}

Page | 12
Lab Manual of Fundamentals of Database Systems

p {margin-left:20px;}
body {background-image:url("images/back40.gif");}

Internal Style sheet


An internal style sheet should be used when a single document has a unique style. You define
internal styles in the head section of an HTML page, by using the <style> tag, like this:
<head>
<style>
hr {color:sienna;}
p {margin-left:20px;}
body {background-image:url("images/back40.gif");}
</style>
</head>
Inline Style sheet
An inline style loses many of the advantages of style sheets by mixing content with presentation.
Use this method sparingly!
To use inline styles you use the style attribute in the relevant tag. The style attribute can contain any
CSS property. The example shows how to change the color and the left margin of a paragraph:
<p style="color:sienna;margin-left:20px">This is a paragraph.</p>

Exercise 1: Practice applying CSS to HTML pages


Example
body
{
background-color:#d0e4fe;
}
h1
{
color:orange;
text-align:center;
}
p
{
font-family:"TimesNewRoman";
font-size:20px;
}
.myclass
{
font-family:"TimesNewRoman";
font-size:20px;
}

Save the above in a style.css file and then apply in html as external style sheet by adding
<link href="style.css" rel="stylesheet" type="text/css" />
Please try all the selectors (given above) in your html e.g.<td class=”myclass”>

Page | 13
Lab Manual of Fundamentals of Database Systems

What is JavaScript?
• A scripting language is a lightweight programming language.
• JavaScript is programming code that can be inserted into HTML pages.
• JavaScript inserted into HTML pages, can be executed by all modern web browsers.

UsageofJavaScript
• Writing Into HTML Output
document.write("<h1>This is a heading</h1>");
• Reacting to Events
<button type="button" onclick="alert('Welcome!')">Click Me!</button>
• Changing HTML Content
x=document.getElementById("demo") //Find the element
x.innerHTML="Testing… “;
• Changing HTML Styles
x=document.getElementById("demo") //Find the element
x.style.color="#ff0000"; //Change the style
• Validate Input
varnum=document.getElementById("demo") .value //demo is a textbox
if (num==null|| num==””)
{alert("Enter a value please")};

How to apply JavaScript


To insert a JavaScript into an HTML page, use the <script> tag.
The <script> and </script> tells where the JavaScript starts and ends.

There are two ways of inserting JavaScript:

a. Internal JavaScript
b. External JavaScript

Internal JavaScript
You can place an unlimited number of scripts in an HTML document.
Scripts can be in the <body> or in the <head> section of HTML, and/or in both.
It is a common practice to put functions in the <head> section, or at the bottom of the page. This
way they are all in one place and do not interfere with page content.
<!DOCTYPE html>
<html>
<head>
<scriptlanguage="javascript">
function myFunction()
{
document.getElementById("demo").innerHTML="My First JavaScript Function";
Page | 14
Lab Manual of Fundamentals of Database Systems

}
</script>
</head>
<body>
<h1>My Web Page</h1>
<p id="demo">A Paragraph</p>
<button type="button" onclick="myFunction()">Try it</button>
</body>
</html>
External JavaScript
Scripts can also be placed in external files. External files often contain code to be used by several
different web pages.
External JavaScript files have the file extension .js.
To use an external script, point to the .js file in the "src" attribute of the <script> tag:
<!DOCTYPE html>
<html>
<body>
<script src="myScript.js"language="javascript"></script>
</body>
</html>

Exercise 2: Practice JavaScript


Write a JavaScript function to convert Celsius into Fahrenheit and vice versa in HTML using
JavaScript on input controls. A sample user interface is shown in Figure2 below

GUI should be like this

Figure 2

Exercise 3: Practice CSS and JavaScript

You are required to design a login web page that will have username and password text fields as
shown below in figure3:

Page | 15
Lab Manual of Fundamentals of Database Systems

Figure 3

Requirements:

Default Setting (When the page is loaded)

1. Everything in the username field row must be center aligned with font = arial, using CSS
2. Everything in the password field row must be right aligned with font = courier, using CSS

On Validate button you need to do the following:


Check if anything has been entered in the username and password fields.

• If a field is empty then the background color of the whole row must be set to "RED".
• If a field is NOT empty then the background color of the whole row must be set to
"YELLOW".

Post lab Questions

Add the following feature in your exercise 3.

On Reset button you need to do the following:

Bring the page in the default state i.e. the state when page was loaded.

NOTE: You are required to use JavaScript and CSS to perform the above mentioned
functionality.

Page | 16
Lab Manual of Fundamentals of Database Systems

EXPERIMENT 3
Introduction to SQL Server 2012 DBMS
Objective

• Familiarize studentswith SQL Server 2008 that is anRDMS by Microsoft


• Table creation, definition through script.
• Data import and export from files to DBMS (tables) using SQL import export utility.

SQL Server 2008 Installation:


SQL Server installation and configuration steps are given in the SQL server 2008 installation
guide.ppt lying in the lab folder. This is to help the students in installing the server on their personal
machines and get a know how of SQL architecture and its components.

Exercise 1: Creating relational database using SQL server management studio


designer

Step 1:Open SQL server management studio

Start->Program Files ->SQL server 2008 -> SQL server management studio

Enter your server name as “cactus” username as “lab” password as “123456789” as shown in figure1
below

Figure 1

To add new Database Right click on Database folder and select New Database. Name this database
as your rollnumber (beginning with letter L) as shown in figure2 below.
Page | 17
Lab Manual of Fundamentals of Database Systems

Figure 2

Step 2: Creating Tables through script in your database

The SQL DDL code given in the company.sql file (present in the lab folder) belongs to the relational
model shown in Figure3 below:

Figure 3

Please spend a few minutes going through the code in the company.sql file.

Now click on “New Query” after selecting your own database in the drop down as shown in Figure 4

Page | 18
Lab Manual of Fundamentals of Database Systems

Figure 4

• In the SQL window that opens, copy the code from company.sql file and, paste it as shown in
Figure 5.
• Change use [your database] to the name of the database you created (your rollnumber).
• Now click on execute.
• If all goes well, you would see “command executed successfully” message and on expanding
the tables folder in your database you would see the table that have just been created for you.

Figure 5

Page | 19
Lab Manual of Fundamentals of Database Systems

Exercise 2: Import data in to employee table using Import Export utility

Start->Program Files ->SQL server 2008 -> Import and Export data

Select your Data source as Microsoft Excel as shown in Figure 6 (as data that you are going to
import is present in the company.xls file. You have to repeat the following steps for all the tables
that you created in Exercise1.

Figure 6

Don’t forget to check “First row has column names”. Click on Next.

Select your destination database as shown in Figure 7.

Figure 7

Click Next button .

Page | 20
Lab Manual of Fundamentals of Database Systems

Select the first option on next screen as given below in figure 8

Figure 8

In the next screen that comes up, please make sure you have selected everything as given in the
screen shot below in figure9

Figure 9

Page | 21
Lab Manual of Fundamentals of Database Systems

Now click on “Edit Mappings” button and on the next screen make sure that the destination columns
are correctly selected as shown in figure10 below.

Figure 10

Click OK and then click Next to move to next screen till you get to the screen with “Finish” Button.
In the screen that comes up (figure11) you would see that 8 rows of data would have been
transferred to the employee table, if everything went fine.

Page | 22
Lab Manual of Fundamentals of Database Systems

Figure 11

Selecting Data
Task 1: Selecting data from the table using selection Query
Start->Program Files ->SQL server 2008 -> Management studio
Select your database
Open Query window and type
Select * from employee
Execute Query.

Figure 12

Page | 23
Lab Manual of Fundamentals of Database Systems

Exercise 3: Import data in to the other tables of company database using


Import Export utility
Please repeat the steps in Exercise2 to import data into the rest of the tables. Please make sure
that you follow the following order while importing the data

1. Dependent table
2. Department table
3. Project table
4. Dept_locations table
5. Works_on table

Run the following script in SQL Server after having successfully imported data in all the tables to
get your worked checked
use [your database]
select * from employee

select * from department

select * from dependent

select * from dept_locations

select * from project

select * from works_on

Post Lab Questions:

1. Write SQL script to create the database with the given relational data model given
below:

Book
bookID bookName author

Author
authorID authorName authoraddress

Page | 24
Lab Manual of Fundamentals of Database Systems

2. Import the given data in the table, you need to include screen shots of the data present
in the tables after executing the select statement.

Book
bookID bookName author
1 Chamber of Secrets 101
2 Alchemist 102
3 Philosopher’s stone 101

authorID authorName authoraddress


101 J K Rowling UK
102 Paulo Coelho Brazil

Page | 25
Lab Manual of Fundamentals of Database Systems

EXPERIMENT 4
Introduction to SQL and DDL
Objective
• Familiarize students with the SQL DDL commands
• Enable students to use the basic DML commands (in order to check the working of above
DDL commands)

SQL (Structured Query Language)


SQL commands can be broadly categorized under the following four types:

• DDL
Data Definition Language (DDL) statements are used to define the database structure or
schema. Some examples:
CREATE - to create objects in the database
ALTER - alters the structure of the database
DROP - delete objects from the database
TRUNCATE - remove all rows from a table
• DML
Data Manipulation Language (DML) statements are used for managing data within schema
objects. Some examples:
SELECT - retrieve data from the a database
INSERT - insert data into a table
UPDATE - updates existing data within a table
DELETE - deletes all records from a table, the space for the records remain

• DCL
Data Control Language (DCL) statements. Some examples:
GRANT - gives user's access privileges to database
REVOKE - withdraw access privileges given with the GRANT command
• TCL
Transaction Control (TCL) statements are used to manage the changes made by DML
statements. It allows statements to be grouped together into logical transactions.
COMMIT - save work done
SAVEPOINT - identify a point in a transaction to which you can later roll back
ROLLBACK - restore database to original since the last COMMIT

Page | 26
Lab Manual of Fundamentals of Database Systems

Exercise1: Practice DDL commands using SQL server management studio

Step1: Login to your database


• Open SQL server management studio via Start->Program Files ->SQL server 2008 -> SQL
server management studio
o enter your server name as “cactus” username as “lab” password as “123456789” or
use server name as “172.16.1.254” and password as “12345678” depending on what
you used in the last lab.
• Select your database

Step2: Create a schema


• Click on “New Query”
• In the window (Query Manager) that comes up run the following command
Use [your_own_DB_created_in_lab3]
create schema lab4

Step3: Create table command

• Run the following statement in your own database


CREATE TABLE lab4.School(
schID [int] NOT NULL,
schName [varchar](50) NULL,
schdeanID [int] NULL,
)

CREATE TABLE lab4.Staff(


staffID [int] NOT NULL,
staffName [varchar](50) NULL,
staffRole [varchar](50)
)
• Refresh your database and verify the results from designer on left

Step3: Drop table command


• Run the following statement in your own database

drop table lab4.school

• Refresh your database and verify the results from designer on left

Step4: Primary key on a new table


• Recreate the table dropped in step3, this time with the primary key constraint in place by
running the following command
CREATE TABLE lab4.Staff(
staffID [int] NOT NULL,

Page | 27
Lab Manual of Fundamentals of Database Systems

staffName [varchar](50) NULL,


staffRole [varchar](50),
constraintstaffPK primary key (staffId)
)
• Refresh your database and verify the results from designer on the left by expanding Keys
under Staff table

Step5: Primary key on an existing table via ALTER table command

• Using your own database run the following command

Alter TABLE lab4.School add constraint schPK primary


key(schID)

• Refresh your database and verify the results from designer on the left by expanding Keys
under School table

Step6: Set Foreign Key on new table


• Drop table school (you know how to do that now)

• Recreate the table school by running the following statement


CREATE TABLE lab4.School(
schID [int] NOT NULL primary key,
schName [varchar](50) NULL,
schdeanID [int] NULL,
constraintdeanFK foreign key (schdeanID) references
lab4.Staff(staffId)
)

Step7: Drop Foreign Key constraint via Alter table command


• Using your own database run the following command
Alter table lab4.school drop constraint deanFK

Step8: Add Foreign Key constraint to an existing table via Alter table command
• Using your own database run the following command
Alter table lab4.school add constraint deanFKforeign key
(schdeanID) references lab4.Staff(staffId)

Step9: Add Foreign key constraint to set behavior on delete/update


• Drop the deanFK foreign key constraint added in step8 above
• Recreate the foreign key constraint on school table to set behavior on update and delete by
running the following command
Altertable lab4.school addconstraint deanFK foreign
key(schdeanID)references staff(staffID)
ondelete set null on update cascade

Page | 28
Lab Manual of Fundamentals of Database Systems

Step10: Check the behavior of the foreign key constraint set above by inserting a few rows in
both the tables and then deleting and updating rows in Staff table

• Run the following insert commands to populate the two tables


Insert into lab4.staff values (101, ‘Ahmed’, ‘Principal’)
Insert into lab4.staff values (102, ‘Ali’, ‘Head Teacher’)
Insert into lab4.staff values (103, ‘Salman’, ‘Teacher’)
Insert into Lab4.staff(staffName, staffId) values (‘Fatima’,
104)

Insert into lab4.school values (1, ‘DPS’, 101)


Insert into lab4.school values (2, ‘LGS’, 102)
Insert into lab4.school values (3, ‘BeaconHouse’, 103)

• Select Data from the two tables by running the following commands
Select * from lab4.staff
Select * from lab4.school

• Update Data in Staff table by running the following command


Update lab4.staff set staffId=106 where staffId=103

Check the behavior on update by selecting data from the tables


Select * from lab4.staff
Select * from lab4.school

• Delete Data in Staff table by running the following command


Delete from lab4.staff where staffId=102

Check the behavior on delete by selecting data from the tables


Select * from lab4.staff
Select * from lab4.school

Step11: Add column to an existing table


Alter table lab4.school add schAddress varchar(100)

Step12:Remove column from an existing table


Alter table lab4.school drop column schAddress

Step13: TRUNCATE table


TRUNCATE removes all rows from a table while structures still persists.
i. Insert 5 new rows in school table
ii. Nowexecute truncate command as shown
truncate table lab4.school
iii. select data from school table

Page | 29
Lab Manual of Fundamentals of Database Systems

PostLab Questions

director
did name bestRev

movie
mid mname Directed_by

Given the relational model above:


1. Give the table creation statements with all constraints in place
2. Give the DDL statements to drop the primary key and foreign key constraints in real time
3. Explore how you can set primary key constraints on the director table using GUI provided by
SQL Server, include screen shots
4. Explore how you can set foreign key constraints between tables above by using the GUI
provided by SQL Server, include screen shots
5. Explore how Identity column works in SQL server, give the SQL DDL statement to add a
column called Srno in movie table which would be an identity column
6. Give the command needed to make the srno column added above a unique key for the table.
7. List the main differences between truncate and delete commands

Page | 30
Lab Manual of Fundamentals of Database Systems

EXPERIMENT 5
INTRODUCTION TO SQL DML

Objective
• LearnSQL DML commands specially the use of select query, joins and aggregate functions

Exercise1: Practice select command


Login to your own database (lab/<password> on cactus or scorpion) that you created in Lab3 and
practice the following Select commands. Please also analyze the query and the results it is
bringing and write a statement about what the query is returning on a piece of paper.

i. SELECT particular columns from a Table

General syntax:
SELECT <list of columns> FROM <table name>

Example:
Select fname, lname, salary, bdate
From employee

ii. Select specific rows from a table

General Syntax:
SELECT <* or list of columns>
FROM <table name>
WHERE <condition>

Example:
Select fname, lname, salary, bdate
From employee
Where salary >25000

iii. Use of order by

General Syntax:
SELECT <* or list of columns>
FROM <table name>
WHERE <condition>
ORDER BY <list of columns>

Example:
Select fname, lname, salary, bdate

Page | 31
Lab Manual of Fundamentals of Database Systems

From employee
Where salary >25000
Order by salary desc, fname

iv. Use of DISTINCT

Example:
Select distinct salary
From employee

v. Use of built in functions

Example:
Select datediff(yy, bdate,GETDATE())age,
fname from employee

vi. Use of like and between and null comparisons

Examples:
select fname, Lname, salary, bdate
from employee
where bdate between '01-Jan-1960' and '31-Dec-1969'
and lname like 'S%'

select fname, Lname, salary, bdate


from employee
where super_ssn is null

select fname, Lname, salary, bdate


from employee
where super_ssn is not null

Page | 32
Lab Manual of Fundamentals of Database Systems

Exercise2: Practice select command from multiple tables using inner and outer
joins

vii. INNER JOIN: This join only returns rows when there is at least one match in both the tables
on which the JOIN is being applied.

Example:
select e.fname, e.Lname, d.Dname
from employee e innerjoin department d on e.Dno=d.Dnumber
orderby d.Dname, e.fname

viii. OUTER JOIN:


There are three different Outer Join methods:

 LEFT OUTER JOIN


This join returns all the rows from the left table in conjunction with the matching rows
from the right table. If there are no columns matching in the right table, it returns NULL
values

Example:
select e.fname, e.Lname, d.dependent_name
from employee e leftouterjoindependent d on e.ssn=d.essn
orderby e.fname, e.lname

• RIGHT OUTER JOIN


This join returns all the rows from the right table in conjunction with the matching rows
from the left table. If there are no columns matching in the left table, it returns NULL
values.

Example:
select e.fname, e.Lname, d.dependent_name
fromdependent d rightouterjoin employee e on e.ssn=d.essn
orderby e.fname, e.lname

• FULL OUTER JOIN


This join returns all the rows from the right as well as left table

Example:
First let us insert a department which doesn’t have a manager yet
insertinto department(Dname, dnumber)values ('Accounts', 10)

select e.fname, e.Lname, d.dName


from department d fullouterjoin employee e on e.ssn=d.Mgr_ssn
orderby e.fname, e.lname

Page | 33
Lab Manual of Fundamentals of Database Systems

Exercise3: Practice select command using SQL Aggregate functions


ix. SQL Aggregate functions
Aggregate functions perform a calculation on a set of values and return a single value. These
functions are frequently used with the GROUP BY clause of the SELECT statement.
• AVG() - Returns the average of the values in a group. Null values are ignored.
• COUNT() - Returns the number of items in a group. This function always returns an int data
type value
• MAX() - Returns the maximum value in the expression.
• MIN() - Returns the minimum value in the expression.
• SUM() - Returns the sum of all the values in the expression. SUM can be used on numeric
columns only and it ignores all the NULL values.

General Syntax:
SELECT <list of columns>, <aggregate functions>
FROM <table(s)>
WHERE <condition>
GROUP BY <column(s)>
HAVING < condition based on aggregate function>

Example:
selectCOUNT(*) NumberOfEmployee,AVG(salary)
CompanyAverage,MAX(salary)CompanyMax,MIN(salary)CompanyMin,
SUM(salary) CompanySum
from employee

select d.dname,COUNT(*) DepartmentEmps,SUM(salary) DepartmentSum


from employee e, department d
where e.Dno=d.Dnumber
groupby d.dname

select d.dname,COUNT(*) DepartmentEmps,SUM(salary) DepartmentSum


from employee e, department d
where e.Dno=d.Dnumber
groupby d.dname
havingCOUNT(*)>1 andSUM(salary)>125000

Note the old syntax used for joining tables in last two queries, rewrite them using new
syntax.

EXERCISE 4:

Using your own database, please run the lab5.sql file and write an SQL statement along with
output to answer each of the following queries (it might be helpful if you draw the relational
model for the given SQL script first):

1. List the names and addresses of all guests who are from London, alphabetically ordered by
guest name.

Page | 34
Lab Manual of Fundamentals of Database Systems

2. Display the names of all the guests who have not provided any end date for their
reservations.
3. Display the name and city of the hotels where guest’s from London are staying. The list
should not contain any hotel more than once.
4. Display the average room price of the hotels situated in London.
5. Display the most expensive double, single and family room respectively (across hotels).
6. Display the names of all the hotels along with the number of rooms present in each of them.
7. Display hotel name and city name along with distinct number of room types available in each
of them.
8. Display a sorted list of hotel names alongwith the date for which a room was booked in the
hotel. Please note null should be displayed booking date if the hotel has never been reserved
by anyone.

Post lab Questions

For the same hotel reservation database write SQL statement along with output to answer
following queries:

1. Display the HotelName and RoomNo which was reserved in the year 2001 and 2002, also
display the Guest No who reserved the room at the time.
2. Display the price of the “Family” type room in all hotels along with the HotelNames,
HotelNo, RoomNo. NULL should be shown if a hotel doesn’t have a “Family” type room.
3. Give the number of hotels present in each city.
4. What is the total revenue generated from all double rooms
5. How many different guests have made bookings till May, 2015?
6. Display the price and city name of the cheapest hotel rooms available in each city.
7. Display the name(s) of the guest(s) who have reserved two or more than two rooms in a
hotel.
8. Display the name, city of all the hotels along with the number of reservations it has, in
descending order.

Page | 35
Lab Manual of Fundamentals of Database Systems

EXPERIMENT 6
ADVANCED SQL
Objective:
Practice use of advanced features of the SQL select command like set functions and subqueries.

SET FUNCTIONS
• UNION
• INTERSECT
• MINUS

Exercise1: Practice set functions


Login to your own database (lab/<password> on cactus or scorpion/172.16.1.254) that you created in
Lab3 and practice the following Select commands.

Please also analyze the query and the results it is bringing and write a statement about what
the query is returning on a piece of paper.

i. select fname, lname


from employee e innerjoindependent d on e.ssn=d.essn
union
select e.fname, e.lname
from DEPARTMENT d innerjoin employee e on e.ssn=d.Mgr_ssn
orderby fname, lname

ii. select fname, lname


from employee e innerjoindependent d on e.ssn=d.essn
union all
select e.fname, e.lname
from DEPARTMENT d innerjoin employee e on e.ssn=d.Mgr_ssn
orderby fname, lname

iii. select fname, lname


from employee e innerjoindependent d on e.ssn=d.essn
intersect
select e.fname, e.lname
from DEPARTMENT d innerjoin employee e on e.ssn=d.Mgr_ssn
orderby fname, lname

iv. select fname, lname


from employee e innerjoindependent d on e.ssn=d.essn
except
select e.fname, e.lname
from DEPARTMENT d innerjoin employee e on e.ssn=d.Mgr_ssn
orderby fname, lname

Page | 36
Lab Manual of Fundamentals of Database Systems

SUBQUERIES
There are some guidelines to consider when using subqueries:A sub query must be enclosed in
parentheses.

 A sub query must be placed on the right side of the comparison operator.
 Subqueries cannot manipulate their results internally; therefore ORDER BY clause cannot be
added in to a sub query.You can use an ORDER BY clause in the main SELECT statement
(outer query) which will be last clause.
 Use single-row operators with single-row subqueries.
 If a sub query (inner query) returns a null value to the outer query, the outer query will not
return any rows when using certain comparison operators in a WHERE clause.

3 Subquery Types
• Single-row subquery - where the subquery returns only one row.
• Multiple-row subquery - where the subquery returns multiple rows.
• Multiple column subquery - where the subquery returns multiple columns.

Another type of these subqueries is:


Correlated Subquery.
Are dependent on the their outer query
Will be executed many times while it’s outer queries is being processed, running once for each row
selected by the outer query.
Can be in the HAVING OR WHERE clauses

Exercise2: Practice subqueries

Run the following queries on your own database. Please also analyze the results it is bringing
and write a statement about what the query is returning on a piece of paper. Please also tell
which type (single/multiple row and column, correlated or non-correlated) of subquery it is

v. select fname, lnamefrom employee


where salary =(selectMAX(salary)from employee)

vi. select fname, lname


from employee where ssn in(select essn fromdependent)

vii. select fname, lname


from employee where ssn =any(select essn fromdependent)

viii. select e.fname, e.Lname


from employee e whereexists(select*fromdependent d where d.essn=e.ssn)

Page | 37
Lab Manual of Fundamentals of Database Systems

ix. select d.dname


from department d join dept_locations lo on d.Dnumber=lo.Dnumber
groupby d.Dname, d.Dnumber
havingCOUNT(*)>=all(selectCOUNT(*)from dept_locations li groupby
li.dnumber)

EXERCISE 3:

Write SQL queries to answer the following questions:

1. Give the name(s) of employees who work either on project “ProductX” or on project
“ProductY”
2. Give the name(s) of employees who work both on project “ProductX” or on project
“ProductY”
3. Give the name(s) of employees who work on project “ProductY” but not on project
“ProductX”
4. Give the name(s) of employees who earn the minimum salary.
5. Give the names(s) of employees who work on as many projects as “Jennifer Wallace”. Please
exclude “Jennifer Wallace” from the list.
6. Give the names(s) of employees who work on a project which is not controlled by their own
department.

Post lab Questions

Using the same hotels database as created in Lab 5, write SQL statement along with output to answer
following queries:

1. Give the name(s) of guest who have booking either for Watergate or Latham hotel.
2. Give the name(s) of guest who have booking both for Watergate and Latham hotel.
3. Give the name(s) of guest who have booking for Latham but not for Watergate hotel.
4. Display the name of the guest who has stayed in maximum number of hotels
5. Display the name of the hotel with as many rooms as Latham hotel
6. Display the name of the hotel with the most expensive room

Page | 38
Lab Manual of Fundamentals of Database Systems

EXPERIMENT 7
Views and Stored procedures
Objective

• Lear how to create and Execute different views


• Lear how to create and Execute Stored Procedures with parameters
• Lear how to create and Execute Stored Procedures without parameters

Views
A database view is a stored query that returns data from one or more database tables. The stored
query, or view, is a virtual table. Once you have defined a view, you can reference it just as you
would any other table in a database. Since the view is the result of a stored query, it does not contain
a copy of the data itself. Instead, it references the data in the underlying base tables.

Advantages of Views:
A view can provide additional security. By creating a view and creating the necessarily privileges,
you can ensure that the users are only able to retrieve and modify data that is exposed by that view.
Users will not be able to see or access data in the underlying tables that is not exposed by the view.
Views can reduce query complexities. By creating and storing complex queries and exposing them
in the form of a view, the data from the view can be extracted using much simpler queries.
Since a database view is a stored query, not a copy of the actual data, views consume very little
space.

Examples:
Some examples of the ways views are used are:
• To combine data from multiple tables into a single virtual table that can be queried using
basic statements.
• To partition a complex table into multiple virtual tables that are simpler to query. For
example, if a database table contains sales data from the past 10 years, views can be created
and represented using tables names such as SalesData2000 or SalesData2001.
• To aggregate data and perform calculations. The view (stored query) can request the
database engine to sum or average data in underlying tables. These sums or averages can
then be queried more easily.

Creating a View
Below is the general syntax for creating a View:

CREATEVIEW [View_Name]
AS
[SELECT Statement]

Page | 39
Lab Manual of Fundamentals of Database Systems

For example:
CREATE VIEW v_employeeNames
As
SELECT fname, lnameFROM employee

which will create a View with the name customerData that will only contain customerNmae.

Get result from a View:

This is similar to a Select statement:


select * from v_employeeNames

Modify an existing View


Alter VIEWv_employeeNames
As
SELECT ssn, fname, lnameFROM employee

Drop a View
DROP VIEW v_employeeNames

Stored Procedures

Overview:

A stored procedure is nothing more than prepared SQL code that you save so you can reuse the code
over and over again. So if you think about a query that you write over and over again, instead of
having to write that query each time you would save it as a stored procedure and then just call the
stored procedure to execute the SQL code that you saved as part of the stored procedure.

In addition to running the same SQL code over and over again you also have the ability to pass
parameters to the stored procedure, so depending on what the need is the stored procedure can act
accordingly based on the parameter values that were passed.

Stored procedures are useful in the following circumstances:

• If a database program is needed by several applications, it can be stored at the server and
invoked by any of the application programs. This reduces duplication of effort and improves
software modularity.

• Executing a program at the server can reduce data transfer and communication cost between
the client and server in certain situations.

• These procedures can enhance the modeling power provided by views by allowing more
complex types of derived data to be made available to the database users. Additionally, they

Page | 40
Lab Manual of Fundamentals of Database Systems

can be used to check for complex constraints that are beyond the specification power of
assertions and triggers.

The general form of declaring stored procedures is as follows:

CREATE PROCEDURE <procedure name> (<parameters>)


<Local declarations>
<Procedure body>;

The parameters and local declarations are optional, and are specified only if needed.

There are various options that can be used to create stored procedures. In these next few topics we
will discuss creating a simple stored procedure to more advanced options that can be used when
creating stored procedures.

Stored Procedure (Without Parameters)

In the example given below we will just select employee names from employee table. The given
procedure has no parameter and simply returns the result of query.

To create this procedure that returns employee’s names you would run the following statement:

createprocedure getEmployeeNames
as
select fname, lname from employee

To execute this procedure you would simply run:


EXEC getEmployeeNames
Or simply
getEmployeeNames

Stored Procedure (With Parameters)

The real power of stored procedures is the ability to pass parameters and have the stored procedure
handles the differing requests that are made.

In the example given below we will query the employee table but instead of getting back all records
we will limit it employee living in just a particular city.

Here we have one parameter city of type varchar defined in procedure. The syntax for defining
parameter can be seen from below example.
createprocedure getEmployeeAddress @City varchar(20)
as
select fname, lname,addressfrom employee
whereaddresslike'%'+@City+'%'

Page | 41
Lab Manual of Fundamentals of Database Systems

To call this procedure we would run the following statement:


exec getEmployeeAddress@City='Houston'

If you try to execute the procedure without passing a parameter value you will get an error message
such as the following which states the procedure was expecting a parameter which was not provided.

Msg 201, Level 16, State 4, Procedure getEmployeeAddress, Line 0


Procedure or function 'getEmployeeAddress' expects parameter '@City', which was
not supplied.

Default Parameter Values:

In most cases it is always a good practice to pass in all parameter values, but sometimes it is not
possible. So in the example given below we use the NULL option to allow you to not pass in a
parameter value. If we create and run this stored procedure as is, it will not return any data, because
it is looking for any City values that equal NULL.

alterprocedure getEmployeeAddress @City varchar(20)=NULL


as
select fname, lname,addressfrom employee
whereaddresslike'%'+@City+'%'

We could change this stored procedure and use the ISNULL function to get around this. So if a
value is passed it will use the value to narrow the result set and if a value is not passed it will return
all records.

alterprocedure getEmployeeAddress @City varchar(20)=NULL


as
select fname, lname,addressfrom employee
whereaddresslike'%'+ISNULL(@City,address)+'%'

Multiple Parameters:

We can define multiple parameters by listing each parameter and the data type separated by a
comma. Following example shows how to make procedure with multiple parameters.

createprocedure getEmployeeDetails @City varchar(20)=NULL, @pSal int=NULL


as
select*from employee
whereaddresslike'%'+ISNULL(@City,address)+'%'
and salary=isnull(@pSal, salary)

To execute the above procedure, you could do any of the following:

Exec getEmployeeDetails

getEmployeeDetails @City='Houston'

Exec getEmployeeDetails @City='Houston', @pSal=55000

Page | 42
Lab Manual of Fundamentals of Database Systems

Output Parameter:

So far we have seen how to pass parameters into a stored procedure, but another option is to pass
parameter values back out from a stored procedure. One option for this may be that you call another
stored procedure that does not return any data, but returns parameter values to be used by the calling
stored procedure.

Setting up output parameters for a stored procedure is basically the same as setting up input
parameters; the only difference is that you use the OUTPUT clause after the parameter name to
specify that it should return a value. The output clause can be specified by either using the keyword
"OUTPUT" or just "OUT".

createprocedure getEmployeeCount @City varchar(20)=NULL, @empCount intOUT


as
select @empCount=COUNT(*)from employee
whereaddresslike'%'+ISNULL(@City,address)+'%'

We can also use output instead of out in the procedure.

To call this stored procedure we would execute it as follows. First we are going to declare a
variable, execute the stored procedure and then select the returned valued.
Declare @empCnt int
Exec getEmployeeCount'Houston', @empCnt output
select @empCnt

Deleting a Stored Procedure:

To drop a single stored procedure you use the DROP PROCEDURE or DROP PROC command as
follows.

dropproc getEmployeeCount

dropprocedure getEmployeeDetails

OR dropprocedure lab7.getEmployeeDetails
if the procedure exists within a schema named as Lab7

Modifying an Existing Stored Procedure:

To change the stored procedure and save the updated code you would use the ALTER
PROCEDURE command as follows.

alterprocedure getEmployeeAddress @City varchar(20)=NULL


as
select fname, lname,addressfrom employee
whereaddresslike'%'+ISNULL(@City,address)+'%'

Page | 43
Lab Manual of Fundamentals of Database Systems

InLab Questions:

Using your own database (created in Lab3), write an SQL statement along with output to answer
each of the following queries:

1. Create a view called v_EmployeeInfo that displays the employees’ name, salary and number
of dependents s/he has. Please note 0 should be displayed if the employee has no dependent.
The output should be sorted on employee names

2. Remove from the database the view called v_EmployeeInfo

3. Create a store procedure called p_getManagers_with_Deps that outputs the names of


managerswho have a dependent.

4. Modify the above procedure (question 3) to display the salaries of such employees as well as
their names.

Post lab Questions

1. Create a stored procedure called “SP_NewEmployeeDetail” which should insert the


following details from Employee table in to a new table “T_EmployeeDetail” .The table can
be manually created with the selection of following attributes.

EmployeeSSN, Name, salary, Address

2. Create a stored procedure that returns the maximum salary earner of the department whose
name is given as parameter.

3. Create a view that displays the name and salary of the employee who is working on the
maximum number of projects.

Page | 44
Lab Manual of Fundamentals of Database Systems

EXPERIMENT 8
Triggers
Objective

• Practical implementation of SQL triggers


• Learn how to Create/Alter/drop DML and DDL triggers

Overview:

A trigger is a special kind of stored procedure that automatically executes when an event occurs in
the database server. An SQL trigger may call stored procedures or user-defined functions to perform
additional processing when the trigger is executed.

Unlike stored procedures, an SQL trigger cannot be directly called from an application. Instead, an
SQL trigger is invoked by the database management system on the execution of a triggering insert,
update, or delete operation. The definition of the SQL trigger is stored in the database management
system and is invoked by the database management system, when the SQL table, that the trigger is
defined on, is modified.

Triggers can be divided into two main categories

• DML Triggers
• DDL Triggers

DML Triggers

DML triggers is a special type of stored procedure that automatically takes effect when a data
manipulation language (DML) event takes place that affects the table or view defined in the trigger.
DML events include INSERT, UPDATE, or DELETE statements. DML triggers can be used to
enforce business rules and data integrity, query other tables, and include complex Transact-SQL
statements. The trigger and the statement that fires it are treated as a single transaction, which can be
rolled back from within the trigger.

Basically, DML triggers are classified into two main types: -

(i) After Triggers (For Triggers)


(ii) Instead Of Triggers

Please run the script.sql file given in the Lab folder using your own database to create the table used
for today’s lab.

Page | 45
Lab Manual of Fundamentals of Database Systems

After Triggers (For Triggers)

These triggers run after an insert, update or delete on a table. They are not supported for views.

Given below we have a trigger that is fired after an update on the table.

CREATE TRIGGER Trigger_ForUpdate


ON DBO.TriggerEmployee
FOR UPDATE
AS
UPDATE TriggerEmployee
SET Description = 'changed with For update trigger'
--WHERE EmployeeID= 1

To fire the trigger we can perform update on table TriggerEmployee using

UPDATE TriggerEmployee
SET Name = 'New Name'
WHERE EmployeeID= 4

Select data from above table to see that the trigger fired and description got updated.

Similarly we can make after triggers or For Triggers for insert and delete as well.

How to use inserted or deleted rows:

First refresh the TriggerEmployee table by running the script given below:
--refreshing the data
truncate table TriggerEmployee
insert into TriggerEmployee (Name,
EmployeeID,ContactID,ManagerID,Gender,Description) values
('Ahmed',1,2,2,'M','xyz')
insert into TriggerEmployee (Name,
EmployeeID,ContactID,ManagerID,Gender,Description) values
('Osama',2,1,2,'M','sadsd')
insert into TriggerEmployee (Name,
EmployeeID,ContactID,ManagerID,Gender,Description) values
('Qasim',3,1,2,'M','sadsff')

select * from triggerEmployee


go

Now modify the Trigger_ForUpdate trigger by running the script given below:
alter TRIGGER Trigger_ForUpdate
ON DBO.TriggerEmployee
FOR UPDATE
AS
declare @Employeeidint -- variable declaration
-- get the value from the table of employee id that was updated
select @Employeeid=EmployeeID from inserted
UPDATE TriggerEmployee

Page | 46
Lab Manual of Fundamentals of Database Systems

SET Description = 'changed with For update trigger'


WHERE EmployeeID= @EmployeeID

go
UPDATE TriggerEmployee
SET Name = 'New Name'
WHERE EmployeeID= 2
go

select *from TriggerEmployee


go

Instead Of Triggers:

These can be used as an interceptor for anything that anyone tried to do on our table or view. If you
define an Instead Of trigger on a table for the Delete operation, then try to delete rows, and they will
not actually get deleted (unless you issue another delete instruction from within the trigger).
We have 3 types of instead of triggers.

(a) INSTEAD OF INSERT Trigger.


(b) INSTEAD OF UPDATE Trigger.
(c) INSTEAD OF DELETE Trigger.

Example of instead of insert trigger

create TRIGGER SampleTrigger_select


ON DBO.TriggerEmployee
INSTEAD OF INSERT
AS
SELECT * FROM TriggerEmployee
--print 'sorry this table cannot be modified'

go

INSERT INTO TriggerEmployee(EmployeeID,NAME,ContactID,ManagerID,Gender)


VALUES(5, 'Instead of insert "Select Trigger" ' , 1108, 1, 'M' )

go

SELECT * FROM TriggerEmployee -- NO CHANGE IN THE TABLE

Go

Instead of update and delete triggers can be made using similar way as well. Below is an example of
an intead of delete trigger:

create TRIGGER [dbo].[T_DeleteEmployee]


ON [dbo].TriggerEmployee
INSTEAD OF delete
AS
IF
(

Page | 47
Lab Manual of Fundamentals of Database Systems

SELECT COUNT(*)
FROM TriggerEmployee A

) >0

BEGIN
PRINT 'CAN NOT BE deleted'
END

go

DELETE from TriggerEmployee WHERE EmployeeID= 1


go
select *From TriggerEmployee
go

DDL Triggers

DDL triggers, like regular triggers, fire stored procedures in response to an event. However, unlike
DML triggers, they do not fire in response to UPDATE, INSERT, or DELETE statements on a table
or view. Instead, they fire in response to a variety of Data Definition Language (DDL) events. These
events primarily correspond to SQL statements that start with the keywords CREATE, ALTER, and
DROP.

Use DDL triggers when you want to do the following:


• You want to prevent certain changes to your database schema.
• You want something to occur in the database in response to a change in your database
schema.
• You want to record changes or events in the database schema.

Example of DDL trigger fired on drop_table event


CREATE TRIGGER [T_DeleteTable]
ON DatabASE
FOR DROP_TABLE
AS
PRINT 'CAN NOT BE dropped'
RollBack -- we dont have instead of in DDL so we use rollback
go

To fire the trigger we can try to drop any table of the database on which trigger was defined.
DROP TABLE TriggerEmployee
go

Example of DDL trigger fired on alter_table event

create TRIGGER [T_AlterTable_DT]


ON DatabASE
FOR ALTER_TABLE
AS
Page | 48
Lab Manual of Fundamentals of Database Systems

PRINT 'Table alterdsuccesfully'

go
To fire the trigger we can try to alter any table of the database on which trigger was defined.

ALTER TABLE TriggerEmployee ALTER COLUMN [NAME] VARCHAR(60)


-- select * from [TriggerEmployee]
go

InLabQuestions:

Please run the university.sql file using your own database before proceeding with the exercises.

1. We have FAST university database in which we are keeping track of students and their
departments and which course they are enrolled .The university hires you to make following
changes to their database. The University Database script is placed in the manual folder.

a) The academic officer is concerned with database auditing so he decides to maintain a record
of changes made to database. Create a table Auditing in database with a column AuditId and
LastChangeOn . Create triggers on student, department tables so that when ever any change
is made on these tables the date of change gets stored in the Auditing table.

b) Though academic officer was pretty much satisfied with your last change but after few
months he feels something is missing in auditing table so he ask to change the structure of
the audit table . So now he want to store proper information like

23/09/13 table updated with id=5


23/10/13 table deleted with id=1

So make appropriate change in triggers to perform the operation.

Post lab Questions

1. The academic officer also wants to make sure no one insert, update or deletes department
information from the database. As university has only 3 departments CS, Business and Electrical
and that are already present in database. So create a trigger that will not let anyone to change the
department table.
2. The academic officer was very happy with your last changes in university database So he hires
you again on contract basis to make few more changes to database. So perform following
changes to the university database.
a) The audit log we made will be useless if someone delete the record from it. So he wants to
have a security measure on the table so that no one is able to delete any record or update any
record from the Auditing table.

Page | 49
Lab Manual of Fundamentals of Database Systems

EXPERIMENT 9
DATA MODELING USING ERWIN
Objective

• Familiarize you with Erwin Data modeling tool.

Introduction
ERwin is a popular data modeling tool. The product supports a variety of aspects of database design,
including data modeling, forward engineering (the creation of a database schema and physical
database on the basis of a data model), and reverse engineering (the creation of a data model on the
basis of an existing database) for a wide variety of relational DBMS. This brief tutorial steps you
through the process of creating a data model using Erwin. Creation of a basic data model
(Conceptual data model)

Creation of a basic data model


The Entities involved in this model include: Employee, Department.

From the File Menu choose to create a new model: File->New

As shown in Figure 1 below

Figure 1: Create a new model

Page | 50
Lab Manual of Fundamentals of Database Systems

The next dialog box, shown in Figure 2, will ask you to choose the template to be used to create the
new model. Choose Logical/Physical as the new model type. This choice will allow us to switch
back and forth easily between a logical model (ER Diagram) and a physical model (database
schema).

Figure 2: Selecting a model type

ERwin will now display the main window from which most of your ER diagram development will
be done, as shown in Figure 3.

Figure 3: The ERwin Workplace

Page | 51
Lab Manual of Fundamentals of Database Systems

The ERwin workplace consists of two main parts. On the left is the Model Navigator, which
displays a hierarchy of items of importance, such as entities, domains, and subject areas. On the
right is the Display Window, which will show the ER diagram itself. As you create objects, they
will appear in the display window (if they are visual in nature, like entities), and appear in the
hierarchy within the Model Navigator.

Creating an Entity

To create a new entity, click on the entity icon ( ) on the toolbar, or right-click on the
word Entity in the Model Navigator. If you click on the entity icon, you then should click on the
Display Window where you would like the entity to appear, as shown in Figure 4.

Figure 4: A new entity

Notice that the default name for the entity is E/x, where x is some number (1 in this case). Click on
the Tab key several times and notice what happens. Pressing the tab key cause the focus to cycle
between the three main parts of the Entity: the name of the entity, the primary key attribute(s), and
the non-primary key attribute(s). In general, to modify one of these three parts of the entity, you
will press the Tab key to cycle to the appropriate part of the entity, then type to add or modify that
part of the entity.

Page | 52
Lab Manual of Fundamentals of Database Systems

Right now, press the Tab key until the entity name is highlighted. Then type EMPLOYEE, as shown
in Figure 5.

Figure 5: Changing the name of the entity

At this point, you may wish to save and name your diagram to avoid loss should the system or
application crash.

Adding primary key columns

Once you have changed the name to EMPLOYEE, press the Tab key again to move the focus to the
next part of the Entity, adding a primary key attribute. Then type the name of the primary key
attribute, id, as shown in Figure 6.

Page | 53
Lab Manual of Fundamentals of Database Systems

Figure 6: Adding a primary key attribute

Press the Tab key one more time to bring the focus below the horizontal line in the Entity, where you
will add in a number of non-primary key attributes. Type fname, as shown in Figure 7. When you
have typed fname, press the Enter key (not Tab). Notice what happens. The cursor is now
positioned for you to add another attribute in this same portion of the Entity, the non-primary key
attribute portion. Type another attribute lname.

Page | 54
Lab Manual of Fundamentals of Database Systems

Figure 7: Adding non-primary key attributes

Make another entity, DEPARTMET with primary key dept_id and attributes name and city shown in
the Figure 8 below.

Figure 8: Employee and Department Entities

Page | 55
Lab Manual of Fundamentals of Database Systems

Creating Relationships
ERwin supports the creation of relationships with three basic kinds of connectivity: one-to-one,
one-to-many, and many-to-many. Within the one-to-many category, ERwin allows us to distinguish
between identifyingand non-identifying one-to-many relationships.

Q: What's the difference between identifying and non-identifying relationships?

• An identifying relationship is when the existence of a row in a child table depends on a row
in a parent table. This may be confusing because it's common practice these days to create a
pseudokey for a child table, but not make the foreign key to the parent part of the child's
primary key. Formally, the "right" way to do this is to make the foreign key part of the child's
primary key. But the logical relationship is that the child cannot exist without the parent.

Example: A Person has one or more phone numbers. If they had just one phone number, we could
simply store it in a column of Person. Since we want to support multiple phone numbers, we make a
second table PhoneNumbers, whose primary key includes the person_id referencing the Person table.

We may think of the phone number(s) as belonging to a person, even though they are modeled as
attributes of a separate table. This is a strong clue that this is an identifying relationship (even if we
don't literally include person_id in the primary key of PhoneNumbers).

• A non-identifying relationship is when the primary key attributes of the parent must
not become primary key attributes of the child. A good example of this is a lookup table,
such as a foreign key onPerson.state referencing the primary key of States.state. Person is a
child table with respect to States. But a row in Person is not identified by its state attribute.
I.e. state is not part of the primary key of Person.

A non-identifying relationship can be optional or mandatory, which means the foreign key column
allows NULL or disallows NULL, respectively.

One-to-many Relationships

An non-identifying relationship is created by clicking first on the non-identifying relationship icon (


). To create a non-identifying relationship, click first on this icon, then click on the parent entity
(on the one side of the relationship) and then click on the child entity (on the many side of the
relationship). In this case, you will click first on the non-identifying relationship icon, then on
DEPARTMENT, then on EMPLOYEE. The results are shown in Figure 9 below.

Page | 56
Lab Manual of Fundamentals of Database Systems

Figure 9: Anon-identifying relationship

Double-click on the relationship itself to bring up a dialog box in which we can further refine the
relationship definition. As shown in Figure 10 below.

Page | 57
Lab Manual of Fundamentals of Database Systems

Figure 10: Relationships definition

In the Relationship Cardinality portion of this window, we can determine how many child entity
occurrences may be associated with each parent entity occurrence.

You can further inquire about the functionality of Erwin By going though the guide provided in the
Lab folder.

Forward Engineering
When you have a physical data model, ERwin automatically generates the schema for the target
server as you build the model. Forward Engineering is the process that Erwin uses to transfer the
schema from the data model to the target server.Graphically shown in the Figure 11 below.
When you forward engineer a data model, you can choose to generate a script file, which you can
use to update the database using a database administration tool or you can forward engineer by
directly connecting to the database catalog. Either way, ERwin does the majority of work for you by
generating the script for your target server.

Page | 58
Lab Manual of Fundamentals of Database Systems

Figure 11: Model

Before you forward engineer, you can view the schema, which is a text-based representation of the
database objects that will be created in the database from the script. ERwin uses the data definition
language (DDL) for the target database to write the script. Each time you add an object or property
to your data model, Erwin automatically updates the script file to reflect the change to the data
model.

To Preview the Script File


1. From the File menu, choose Open and locate the .er1 file, which you saved in a previous
exercise.
2. When your .er1 opens, using the Model Type Indicator, switch to the Physical model. Then from
the Tools menu, choose Forward Engineer/Schema Generation.
3. When the Schema Generation dialog appears, click the Preview button at the bottom of the
dialog. The Schema Generation Preview dialog appears as shown in the figure 12 below.

Figure 12: Script File

4. When you are finished previewing the schema, click the Close button to return to the Schema
Generation dialog.

Page | 59
Lab Manual of Fundamentals of Database Systems

To Generate The Script File


1. In the Oracle Schema Generation dialog, click the Report button at the bottom of the dialog
shown in the figure 13 below.

Figure 13

2. In the Save As dialog, in the File Name box, type Mymodel.sqland click Save.
As shown in figure 14.

Figure 14

Reverse Engineering
When you have an existing database from which you want to create a data model, ERwin lets you
reverse engineer the database schema, which is converted by Erwin into a graphical representation of
the database structures. A graphical model of the process is shown below in the Figure 15. The
process of reverse engineering saves considerable time because ERwin does the work of creating the
data model directly from the database.

Page | 60
Lab Manual of Fundamentals of Database Systems

Figure 15: Reverse Engineering

Using The Reverse Engineer Wizard


1. From the Tools menu, choose Reverse Engineer shown in the Figure 16.

Figure 16

2. In the dialog, select Physical as the New Model Type, select Blank Physical Model as the
template, and SQL Server 2000 as the target database.
3. Then click Next. The Reverse Engineer Set Options dialog box appears as shown in Figure 17:

Page | 61
Lab Manual of Fundamentals of Database Systems

Figure 17

4. In Reverse Engineer From, select Script File and then click Browse to locate the My.sqlfile that
you saved in the previous exercise. For the purpose of this exercise, accept the default options in
the remaining areas of the dialog and then click Next.
5. You will see a small dialog with text that describes the database structures that ERwin is reverse
engineering. When the process ends, a new data model appears in the Diagram Windowas shown
in Figure 18.

Figure 18

Page | 62
Lab Manual of Fundamentals of Database Systems

6. From the File menu, choose Save and save this model as My ERwin Model.ER1. When asked if
you want to replace the existing file, click Yes.

InLab Task:
Using Erwin make the following ER diagram as shown in Figure 19:

Figure 19

Post Lab Questions:


1. Forward Engineer the data model you created for the inLab and save the SQL file that gets
generated.
2. Reverse Engineer the testscript.sql file lying in the Lab folder and save the data model that gets
generated.

References
• http://www.isqa.unomaha.edu/wolcott/tutorials/erwin/erwin.html
• http://stackoverflow.com/questions/762937/whats-the-difference-between-identifying-and-
non-identifying-relationships

Page | 63
Lab Manual of Fundamentals of Database Systems

EXPERIMENT 10

Building ASP.net web applications with Database Connectivity


Objective
• Learn creating DataBase Connectivity with ASP.Net Web Application

Create an ASP.net web application


Master pages allow you to create a consistent look and behavior for all the pages (or group of pages)
in your web application.

A master page provides a template for other pages, with shared layout and functionality. The master
page defines placeholders for the content, which can be overridden by content pages. The output
result is a combination of the master page and the content page.

The content pages contain the content you want to display.

When users request the content page, ASP.NET merges the pages to produce output that combines
the layout of the master page with the content of the content page.

For more info Visit

http://www.w3schools.com/aspnet/aspnet_masterpages.asp

http://msdn.microsoft.com/en-us/library/wtxbf3hh.ASPX

The following Exercise will demonstrate how to create and use Master Pages

1) Create a New Project in Visual Studio , Selecting ASP.Net Web Application and .Net
Framework 4 in middle Pane and Visual C# Web in left Pane

Name your project MyWebSite (follow figure 1)

Page | 64
Lab Manual of Fundamentals of Database Systems

Figure 1

2) Add Master Page in you Project, using Add New Item Option from Solution Explorer
(Follow Figure 2 and 3)

Name this Master Page asMyMasterPage.Master

Page | 65
Lab Manual of Fundamentals of Database Systems

Figure 2

Figure 3

Page | 66
Lab Manual of Fundamentals of Database Systems

3) Now we will add CSS file and images in our project that will be used in Styling MasterPage

The Web Template is downloaded from


http://all-free-download.com/free-website-templates/
You can also download template from this website for your Projects
The Template used for This Lab Exercise is
http://all-free-download.com/free-website-templates/snow_glass_215.html

Add The CSS files (MyCSSFile.CSS given in Resource Folder along with Manual) in your Project
using Add Existing Item as shown in Figure 4

Figure 4

Page | 67
Lab Manual of Fundamentals of Database Systems

After Adding CSS file create new Folder in your Project named Images using New Folder option
(As shown in Figure 5)

Figure 5

Now add all the images given in Resources\Images folder in this Images folder
(as shown in figure 6 and 7)

Page | 68
Lab Manual of Fundamentals of Database Systems

Figure 6

Figure 7

Page | 69
Lab Manual of Fundamentals of Database Systems

4) Now open MyMasterPage and Drag Drop Css file in Header (as shown in Figure 8)

Figure 8

After that Open the MasterPage_Body.txt file given in Resources and Copy All the contents ,
Replace everything inside the Body tags of MyMasterPage with this content as shown in the figure 9

Page | 70
Lab Manual of Fundamentals of Database Systems

Figure 9

Page | 71
Lab Manual of Fundamentals of Database Systems

5) Now we create Two Web Forms that will use the Master Pages.

Add New Web Form Using Master Page, Using Add New Item, Name this page as Home.aspx
As shown in figure 10 below

Figure 10

Choose MyMasterPage.Master from Selection Popup as shown in the figure 11

Figure 11

Page | 72
Lab Manual of Fundamentals of Database Systems

Similarly add another Web Form using Master Page in your Project, Name it Search.aspx

Confirm the Web Forms are added form solution Explorer as shown in figure 12

Figure 12

Execute your Project and see the result in Browser, Click on home and search and see the change in
Address bar as shown in figure 13
6)

Figure 13

Page | 73
Lab Manual of Fundamentals of Database Systems

You have successfully created a Master Page and used it in Home Page and Search Pages. Save you
work for the next exercise

Connect with database

The Next Exercise will show how to connect the web site with the SQL databases, and how to
Access the Data

1) First Open TheDataBaseQueries.Script file in resources, and execute it in SQL server, this
will create a New data base with name Lab10Exercise2
, an Items Table , and SearchItems Procedure , we will use the data from this table and result from
this procedure in our Web site

2) Use the Same Web Project in previous Exercise , Create a DataBase Conection String in
Web Config File
FORMAT OF CONNECTION STRING
<connectionStrings>
<addname="SQLDbConnection"
connectionString="Data Source=SQlServerName; Initial Catalog=YouDatabaseName; User
Id=userid; password= password"
providerName="System.Data.SqlClient" />
</connectionStrings>

More info about connection string


http://msdn.microsoft.com/en-us/library/jj653752%28v=vs.110%29.aspx
• Data Source means server name i.e. cactus, (local)
• Initial Catalog means database name which has your table, sp and views
• User Id means login name for database
• password means password for database

An Easy Way to get these values are from SQL server Connect to Server Window as Shown in
Figure 14

Page | 74
Lab Manual of Fundamentals of Database Systems

Figure 14

SAMPLE CONNECTION STRINGS


• Connection string with window authentication for local host
<connectionStrings>
<addname="sqlCon1"connectionString="Data Source=(local);Initial
Catalog=Lab10Excercise2;Integrated Security=True"
providerName="System.Data.SqlClient" />
</connectionStrings>

• Connection string with SQL server authentication for server name MYSQLSERVER
<connectionStrings>
<addname="sqlCon1"connectionString="Data Source=(local);Initial Catalog=Lab10Exercise2;User
ID=sa;password=123"
providerName="System.Data.SqlClient" />

</connectionStrings>

Add your Connection String in Web Config file as shown in figure 15

Page | 75
Lab Manual of Fundamentals of Database Systems

Figure 15

3) Creating DAL --- Data Access Layer, to get Data from SQL

Create New Folder in your Project Named DAL, in this folder Add New Item of type Class and
Name it myDAL as shown in figure 16

Figure 16

Page | 76
Lab Manual of Fundamentals of Database Systems

4) open the myDal.cs file and Add the Reference to Connection String plus , Name Spaces for
SQL and DataSets as shown in figure 17

privatestaticreadonlystringconnString =
System.Configuration.ConfigurationManager.ConnectionStrings["sqlCon1"].ConnectionString;

Figure 17

5) Now Create the a function in myDal Class that will perform a simple select * from Itemquery
on Database and get the result set

Copy paste the function SelectItem() from Function_SelectItems.Txt file as shown in figure 18

Page | 77
Lab Manual of Fundamentals of Database Systems

Figure 18

Page | 78
Lab Manual of Fundamentals of Database Systems

6) Using SelectItems() function to Displaying the result set

Now we display the DataSet returned from SelectItem() on Home page as shown in figure 19

Figure 19

You can see that the Grid Already look like a table , all you need to do is fill the values in it from
your Query
The contents of Grid are changes from Server Side Aspx.csfile,open your Home.aspx.cs file , modify
it (changes are given In Home_aspx_CS.txt file) as shown in the figure 20

Page | 79
Lab Manual of Fundamentals of Database Systems

Figure 20

Execute your Project, and if everything goes right, the Home page should be as shown in the figure
21:

Page | 80
Lab Manual of Fundamentals of Database Systems

You have successfully


used The Result of a
simple Query on your
Website!

Figure 21

Using SQL procedures in Asp.Net

So far we have used a Table form result set of a simple query and displayed on our web site, the
following Exercise will show how to call SQL procedures from ASP.net, how to pass them input
parameters and how to get output parameters and result sets from SQL procedures

We have already create a Web Form Names Search.aspx in our Web Project and SearchItem SQL
procedure, Now we will add search Functionality on our page, by getting the Item Name from user
and querying the database for that item using SearchItemsqL Procedure, the procedure will return
the dataset and output found =1 if any item with that name exists, and if no item is found for that
Item it will output Found = 0.

Open Search.aspx page and modify the Code, (Adding Text box and Button and a Grid to
show the result of search)
Code given in file Search_Aspx.txt

It will look like the figure 22 shown below

Page | 81
Lab Manual of Fundamentals of Database Systems

Figure 22

Open myDal.cs file and Add SearchItems() function in it (code given in Function_Searchitems.Txt
file) as shown in figure 23

Page | 82
Lab Manual of Fundamentals of Database Systems

Figure 23

Use this new Function SearchItem() in Server Side Search.aspx.cs


Open Search.aspx.cs file and modify it as shown in figure 24 (code given in Search_Aspx_CS.txt
file)

Page | 83
Lab Manual of Fundamentals of Database Systems

Figure 24

Execute your project. Type Soap in Text box and Click Search, following results should appear
As in the figure 25

Figure 25

Now Type some random string in Test box and Click Search, Following Results Should Appear
As in the figure 26

Page | 84
Lab Manual of Fundamentals of Database Systems

Figure 26

Post Lab Questions

Make another webpage with search bar in it. It displays only the item with quantity greater than 5
otherwise it should display ‘Out of stock’.

Page | 85
Lab Manual of Fundamentals of Database Systems

EXPERIMENT 11

ASP.net Updation/Deletion via GridView Control and Insertion


Objective

• Familiarize you with Delete through Grid View and Insert via ASP.net web form.

Delete via GridView


As in the last lab we used the Grid Views to display the data from an SQL table , The Grid View can
also be used to delete data from that table , following exercise will demonstrate how to:

1) (If not done in last lab) Create a Data base named <your rollnumber>
2) (If not done in last lab)Create a table named Items and insert values in it using following
queries
Figure 1 s shown for correspondence

--Create table
Create table items
(ItemNo int,
ItemName varchar(15),
TotalUnits int
)
go

--insert values
Insert into items
values
(1,'Soap', 10 )
,(2,'Handwash', 20)
,(3,'Shampoo',5)
go

Figure 1
3) Now Create the following procedure to Delete the Item from Items table , we will call this
procedure from asp.net to delete tuples from Items table as shown in figure 2

CreatePROCEDURE [dbo].[deleteItem]
@ID int
AS
BEGIN
SETNOCOUNTON;

DELETEFROM Items WHERE ItemNo = @ID

Figure 2
Page | 86
Lab Manual of Fundamentals of Database Systems

4) Now in Visual Studio Create a New web project using settings as show in Figure 3

Figure 3

5) Follow the Steps of last manual to create a Master Page (briefed as follows)
• Add The CSS files (MyCSSFile.CSS given in Resource Folder along with Manual) in your
Project using Add Existing Item
• Create new Folder named Images and add all the images given in Resource/Images
• Add Master Page in you Project , using Add New Item Option from Solution Explorer Name
this Master Page as MyMasterPage.Master
• Drag and Drop CSS file in header tag of Master Page, After that Open the
MasterPage_Body.txt file given in Resources and Copy All the contents , Replace everything
inside the Body tags of MyMasterPage with this content

6) Open your Web Config file and add connectivity String in it (as done in last lab, consult
lab11 Manual for details). Change the Initial Catalog to <your rollnumber> (your current
DB) for this exercise

7) Create DAL folder and add new myDAL.cs file in it (as shown in figure 4)

Page | 87
Lab Manual of Fundamentals of Database Systems

Figure 4

8) Open the myDal.cs file and Add the Reference to Connection String plus, Name Spaces for
SQL and DataSets as shown in figure 5
Using System.Data;
Using System.Data.SqlClient;

Private static readonly string connString =


System.Configuration.ConfigurationManager.ConnectionStrings["sqlCon1"].ConnectionString;

Figure 5

Page | 88
Lab Manual of Fundamentals of Database Systems

9) Copy Paste following 2 functions SelectItem() and DeleteItem() in myDal.cs file (ass hown
in figure 6)

publicDataSetSelectItem() //to get the values of all the items from table Items and return
the Dataset
{

DataSet ds = new DataSet(); //declare and instantiate new dataset


SqlConnection con = new SqlConnection(connString); //declare and instantiate new SQL
connection
con.Open(); // open sql Connection
SqlCommandcmd;
try
{
cmd = new SqlCommand("Select * from Items", con); //instantiate SQL command
cmd.CommandType = CommandType.Text; //set type of sqL Command
using (SqlDataAdapter da = newSqlDataAdapter(cmd))
{
da.Fill(ds); //Add the result set returned from SQLCommand to ds
}
}
catch (SqlException ex)
{Console.WriteLine("SQL Error" + ex.Message.ToString()); }
finally
{con.Close(); }

return ds; //return the dataset

}
//////////////////////////////////////////////////////
publicintDeleteItem(int id)
{
SqlConnection con = newSqlConnection(connString);
con.Open();
SqlCommandcmd;
int result = 0;
try
{
cmd = newSqlCommand("deleteItem", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("@ID", SqlDbType.Int).Value = id;
result = cmd.ExecuteNonQuery();
}
catch (SqlException ex)
{ Console.WriteLine("SQL Error" + ex.Message.ToString());
}
finally
{ con.Close();

Figure 6

Page | 89
Lab Manual of Fundamentals of Database Systems

Deletion in GridView

10) Add New Grid in your home.aspx page with ID ItemGrid , Click the Forward Arrow button
and Select Edit Columns as shown in figure 7

Figure 7

The following popup will appear, Expand CommandFieldandAddEdit Update, Cancel and Delete
and click OK as shown in figure 8 below

Figure 8

Page | 90
Lab Manual of Fundamentals of Database Systems

11) Your Grid will have 2 new columns now

Keep the Grid selected and go to its properties, click on Small Lightening Icon, and Change the
Value of Column Row Deleting to ItemGrid_RowDeletingas shown in figure 9

Figure 9

12) Open the Home.aspx.cs file and replace pageload() function with the code given below

protectedvoidPage_Load(object sender, EventArgs e)


{
LoadGrid(); // fill the grid every time page loads

And add two functions LoadGrid() and ItemGrid_RowDeleting and add the code given below.

Page | 91
Lab Manual of Fundamentals of Database Systems

publicvoidLoadGrid()
{
myDALobjMyDal = new myDAL();
ItemGrid.DataSource = objMyDal.SelectItem();//seting data source for this Grid
ItemGrid.DataBind(); //bind the data source to this grid
}// end of loadgrid

Protected voidItemGrid_RowDeleting(object sender, GridViewDeleteEventArgs e)


{
myDALobjMyDal = new myDAL();
GridViewRow row = ItemGrid.Rows[e.RowIndex];
intItemID = Convert.ToInt32(row.Cells[2].Text.ToString());
int result = objMyDal.DeleteItem(ItemID);
if (result == -1)
{
ItemGrid.DataSource = objMyDal.SelectItem();
ItemGrid.DataBind();
}
else
{
string message = "No row deleted";
ClientScript.RegisterOnSubmitStatement(this.GetType(), "alert",

message.ToString());
}

Now execute your project, following results should appear in browser as shown below in figure 10

Figure 10

On Clicking Delete, the corresponding row will delete (check from SQL server as well)
Refer to figure 11

Page | 92
Lab Manual of Fundamentals of Database Systems

Figure 11

Perform Updation via GridView Control


Step1:
First we will add the following code in Home.aspx page under the “<Columns>” tag of GridView
we created earlier as shown below
<Columns>

<asp:CommandFieldShowEditButton="True"/>
<asp:CommandFieldShowDeleteButton="True"/>

<asp:TemplateFieldHeaderText="ItemNo" HeaderStyle-HorizontalAlign="Left">
<EditItemTemplate>
<asp:LabelID="txtItemNo"runat="server"Text='<%# Bind("ItemNo") %>'></asp:Label>
</EditItemTemplate>

<ItemTemplate>
<asp:LabelID="lblItemNo"runat="server"Text='<%# Bind("ItemNo") %>'></asp:Label>
</ItemTemplate>

<HeaderStyleHorizontalAlign="Left"></HeaderStyle>

</asp:TemplateField>
<asp:TemplateFieldHeaderText="ItemName"HeaderStyle-HorizontalAlign="Left">
<EditItemTemplate>
<asp:TextBoxID="txtItemName"runat="server"Text='<%# Bind("ItemName")
%>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:LabelID="lblItemName"runat="server"Text='<%# Bind("ItemName") %>'></asp:Label>
</ItemTemplate>
<HeaderStyleHorizontalAlign="Left"></HeaderStyle>
</asp:TemplateField>

<asp:TemplateFieldHeaderText="TotalUnits"HeaderStyle-HorizontalAlign="Left">
<EditItemTemplate>
<asp:TextBoxID="txtTotalUnits"runat="server"Text='<%# Bind("TotalUnits")
%>'></asp:TextBox>
Page | 93
Lab Manual of Fundamentals of Database Systems

</EditItemTemplate>
<ItemTemplate>
<asp:LabelID="lblTotalUnits"runat="server"Text='<%# Bind("TotalUnits")
%>'></asp:Label>
</ItemTemplate>
<HeaderStyleHorizontalAlign="Left"></HeaderStyle>
</asp:TemplateField>

</Columns>

Figure 14

Now set the “EnableViewState” and “AutoGenerateColumns” properties of the Grid View as
follows in the figure 12

Figure 12

Step2:

Now we will set up all the events in our .aspx page which we will require for implementing Edit
functionality as shown in the following figure 13:

Page | 94
Lab Manual of Fundamentals of Database Systems

Figure 13

Step3:

Now we are set to move to the BLL (Business Logic layer)of this page which is the Home.aspx.cs.
There we will implement all the above create event handling functions.

Replace the Page_Load() function with the following function shown below :

Protected void Page_Load(object sender, EventArgs e)


{ LoadGrid();
}

Following are the functions which you have to copy/paste as well against all the event handling
definitions created above a shown below
Public void LoadGrid()
{myDAL md = new myDAL();
ItemGrid.DataSource = md.SelectItem();
ItemGrid.DataBind();
}
ProtectedvoidItemGrid_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
GridViewRow row = (GridViewRow)ItemGrid.Rows[e.RowIndex];
//==== getting the value from the respective controls=====
LabelitemNo = (Label)ItemGrid.Rows[e.RowIndex].FindControl("txtItemNo");

Page | 95
Lab Manual of Fundamentals of Database Systems

TextBoxItemName = (TextBox)ItemGrid.Rows[e.RowIndex].FindControl("txtItemName");
TextBoxTotalUnits = (TextBox)ItemGrid.Rows[e.RowIndex].FindControl("txtTotalUnits");
//========================================================
intitemNoValue = Convert.ToInt32(itemNo.Text.ToString());
stringitemNameValue = ItemName.Text.ToString();
inttotalUnits = Convert.ToInt32(TotalUnits.Text.ToString());

//=====updating the newly entered values in database====


myDALobjMyDal = newmyDAL();
objMyDal.UpdateItem(itemNoValue, totalUnits, itemNameValue);
//======================================================
ItemGrid.EditIndex = -1;
LoadGrid();
}

ProtectedvoidItemGrid_RowCancellingEdit(object sender, GridViewCancelEditEventArgs e)


{
ItemGrid.EditIndex = -1;
LoadGrid();
}

ProtectedvoidItemGrid_RowEditing(object sender, GridViewEditEventArgs e)


{
ItemGrid.EditIndex = e.NewEditIndex;
LoadGrid();
}

Step 4:

Now moving on to the DAL layer of our application, we will have to create function for Update/Edit
functionality. For that copy paste the following function in to you myDAL.cs file.

publicintUpdateItem(int id, inttotalUnits, stringitemName)


{
SqlConnection con = newSqlConnection(connString);
con.Open();
SqlCommandcmd;
int result = 0;
try
{
cmd = newSqlCommand("UpdateItem", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("@itemNo", SqlDbType.Int).Value = id;
cmd.Parameters.Add("@itemname", SqlDbType.VarChar).Value = itemName;
cmd.Parameters.Add("@totalUnits", SqlDbType.Int).Value = totalUnits;
result = cmd.ExecuteNonQuery();
}
catch (SqlException ex)
{
Console.WriteLine("SQL Error" + ex.Message.ToString());
}
finally {
con.Close();

Page | 96
Lab Manual of Fundamentals of Database Systems

}
return result;
}

Step 5:

Now before executing the application, execute the below script on your database so that the required
procedure for editing functionality is created as shown below.

CREATEPROCEDURE [dbo].[UpdateItem]
@itemNo int, @itemname varchar(100), @totalUnits int
AS
BEGIN SETNOCOUNTON;
Update items set ItemName=@itemname, TotalUnits=@totalUnits
where ItemNo=@itemno;
END

Perform insertion

1) Change the Home.aspx page to look as follows: (Don’t execute now. Use split view )
as shown in figure 14.

Figure 14

Please ensure that the ID property of the three text fields are set asTxtItmNo , TxtItmName and
TxtUnitsrespectively.
On click of the “Add New Item” button copy the following code in Home.aspx.cs as given below
(shows error on insert)

Page | 97
Lab Manual of Fundamentals of Database Systems

protectedvoidinsrtItem_Click(object sender, EventArgs e)


{
intitemNoValue = Convert.ToInt32(TxtItmNo.Text.ToString());
stringitemNameValue = TxtItmName.Text.ToString();
inttotalUnits = Convert.ToInt32(TxtUnits.Text.ToString());

//=====updating the newly entered values in database====


myDALobjMyDal = new myDAL();
objMyDal.insertItem(itemNoValue, totalUnits, itemNameValue);

LoadGrid();
}

In myDAL.cs file Add the following function:

publicintinsertItem(int id, inttotalUnits, stringitemName)


{
SqlConnection con = new SqlConnection(connString);
con.Open();
SqlCommandcmd;
int result = 0;
try
{
cmd = new SqlCommand("InsertItem", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("@itemNo", SqlDbType.Int).Value = id;
cmd.Parameters.Add("@itemname", SqlDbType.VarChar).Value = itemName;
cmd.Parameters.Add("@totalUnits", SqlDbType.Int).Value = totalUnits;

result = cmd.ExecuteNonQuery();
}
catch (SqlException ex)
{
Console.WriteLine("SQL Error" + ex.Message.ToString());
}
finally
{
con.Close();
}

return result;
}//end of insert function

Page | 98
Lab Manual of Fundamentals of Database Systems

Create the following procedure in SQL Server 2014as shown .


CREATE PROCEDURE [dbo].[InsertItem]
@itemNoint,
@itemnamevarchar(100),
@totalUnitsint
AS
BEGIN
SET NOCOUNT ON;
insert into items values(@itemno, @itemname, @totalUnits );
END

Build and run your project. On giving the values and clicking the “Add New Item” button a
new item should get inserted as shown in figure 15.

Figure 15

Post Lab Questions

Make another page which has a search bar in it. The searched item can be updated/deleted.

Page | 99
Lab Manual of Fundamentals of Database Systems

EXPERIMENT 12
ASP.net Passing values across webpages and SQL Injection
Objective

• Familiarize you with how values can be passed across webpages


• Introduce you to SQL injection.

Ways of passing values between ASP.net pages


There are number of ways to transfer values between asp pages

1) Query String
2) Session Variable
3) Application Variable
4) Cookies
and number of others

Below are references which will explain how to transfer values with examples:

http://msdn.microsoft.com/en-us/library/6c3yckfw%28v=vs.100%29.aspx
http://www.codeproject.com/Articles/8055/Transferring-page-values-to-another-page
http://www.codeproject.com/Articles/8350/Passing-information-between-pages-The-NET-way
http://www.codeproject.com/Articles/5876/Passing-variables-between-pages-using-QueryString

Transfer values across ASP.net pages using querystring


In your asp.net project (you can use the one, created in Lab10). Add 2 new webforms named
Login.aspx and Profile.aspx

In Login.aspx, Add the following code within asp:content tag with id=content2 as shown below.

<asp:ContentID="Content2"ContentPlaceHolderID="ContentPlaceHolder1"runat="server">
User:
<asp:TextBoxID="txtusrname"runat="server"></asp:TextBox>
<br/>
Password:
<asp:TextBoxID="txtpassword"runat="server"TextMode="Password"></asp:TextBox>
<br/>
<asp:ButtonID="submit"runat="server"Text="submit"onclick="submit_Click"/>
</asp:Content>

Page | 100
Lab Manual of Fundamentals of Database Systems

In Login.aspx.cs file Add the following code in the submit_Click method


as shown below.
protectedvoidsubmit_Click(object sender, EventArgs e)
{
Response.Redirect("Profile.aspx?Name="+txtusrname.Text+"&pwd="+txtpassw
ord.Text);
}

In Profile.aspx page add a label within the appropriate asp:content tag, as shown
<asp:ContentID="Content2"ContentPlaceHolderID="ContentPlaceHolder1"runat="server">
<asp:LabelID="lblUserName"runat="server"Text="Label"></asp:Label>
</asp:Content>

In Profile.aspx.cs file add the following code as shown

ProtectedvoidPage_Load(object sender, EventArgs e)


{
lblUserName.Text=Request.QueryString["Name"];
}

Build and run your Login.aspx page and see what happens on clicking the submit button.

Page | 101
Lab Manual of Fundamentals of Database Systems

Grid Transfer value


This is a simple example of how to transfer value from grid to other aspx page
Homepage.aspx looks like this in browseras shown in figure 1.

Figure 1

When clicked on Buy it of first row, the ShoppingPage.aspx look like thisas shown in figure 2.

Figure 2

The code ofHomepage.aspx look like thisas shown in figure 3.


Page | 102
Lab Manual of Fundamentals of Database Systems

Figure 3

While on server side of shoppingPage.aspx we can decode query string in such way as described below in figure 4

Figure 4

The second method: if you want to transfer value of grid row and other controls too like customer name and credit
card number, you have to use template field property of gridas shown in figure 5.
Page | 103
Lab Manual of Fundamentals of Database Systems

Figure 5

Add the following templatefield before ItemNo template field in Home.aspx page made in last lab as
shown in figure 6.

<asp:TemplateField>
<ItemTemplate>
<asp:HyperLinkID="h1details"Text="Details"runat="server"
NavigateUrl='<%# "Default.aspx?ItemName="+Eval("ItemName")+"&Qty="+Eval("TotalUnits")%>'/>
</ItemTemplate>
</asp:TemplateField>

Page | 104
Lab Manual of Fundamentals of Database Systems

Figure 6

In Default.aspx Add the following two labels as shown in figure 7.


<asp:LabelID="lbItemName"runat="server"></asp:Label>
<br/>
<asp:LabelID="lbQty"runat="server"></asp:Label>

Figure 7

In page load method of Default.aspx.cs add the following code


lbItemName.Text = Request.QueryString["ItemName"];
lbQty.Text = Request.QueryString["Qty"];

Buid and run your Home.aspx and see what happens on clicking the Details link present in the
gridview

SQL Injection
A SQL Injection attack is a form of attack that comes from user input that has not been checked to
see that it is valid. The objective is to fool the database system into running malicious code that will
reveal sensitive information or otherwise compromise the server.

Page | 105
Lab Manual of Fundamentals of Database Systems

There are two main types of attacks. First-order attacks are when the attacker receives the desired
result immediately, either by direct response from the application they are interacting with or some
other response mechanism, such as email. Second-order attacks are when the attacker injects some
data that will reside in the database, but the payload will not be immediately activated. We will
discuss each in more detail later in this article.

An example of what an attacker might do

In the following example, assume that a web site is being used to mount an attack on the database. If
you think about a typical SQL statement, you might think of something like:

SELECT ProductName, QuantityPerUnit, UnitPrice


FROM Products
WHERE ProductName LIKE 'G%'

The objective of the attacker is to inject their own SQL into the statement that the application will
use to query the database. If, for instance, the above query was generated from a search feature on a
web site, then they user may have inserted the "G" as their query. If the server side code then inserts
the user input directly into the SQL statement, it might look like this:

stringsql = "SELECT ProductName, QuantityPerUnit, UnitPrice "+


"FROM Products " +
"WHERE ProductName LIKE '"+this.search.Text+"%';
SqlDataAdapter da = new SqlDataAdapter(sql, DbCommand);
da.Fill(productDataSet);

This is all fine if the data is valid, but what if the user types something
unexpected? What happens if the user types:

' UNION SELECT name, type, id FROM sysobjects;--

Note the initial apostrophe; it closes the opening quote in the original SQL statement. Also, note the
two dashes at the end; that starts a comment, which means that anything left in the original SQL
statement is ignored.

Now, when the attacker views the page that was meant to list the products the user has searched for,
they get a list of all the names of all the objects in the database and the type of object that they are.
From this list, the attacker can see that there is a table called Users. If they take note of the id for the
Users table, they could then inject the following:

' UNION SELECT name, '', length FROM syscolumns WHERE id = 1845581613;--

This would give them a list of the column names in the Users table. Now they have enough
information to get access to a list of users, passwords, and if they have admin privileges on the web
site.

' UNION SELECT UserName, Password, IsAdmin FROM Users;--

Page | 106
Lab Manual of Fundamentals of Database Systems

Assume that there is a table called Users which has columns called UserName and Password, it is
possible to union that with the original query and the results will be interpreted as if the UserName
was the name of the product and the Password was the quantity per unit. Finally, because the
attacker discovered that there is aIsAdmin column, they are likely to retrieve the information in that
too.

Solution of SQL Injection Attack .net?


From server side you can use this method

string surname = this.surnameTb.Text.Replace("'", "''");


string sql = "Update Users SET Surname='"+surname+"' "+
"WHERE id="+userID;

from client side you can use this method by using JavaScript validation
include JavaScript file in solution or embed same JavaScript code in your aspx
page

Example of sql injection protection is shared with you in SQL-INJECTION SAMPLE-Login.aspx

<asp:Button ID="BtnLogin" runat="server" Text="Login"


onclick="BtnLogin_Click" OnClientClick= "javascript: return
validation(); " />

<script type="text/javascript">
function validation() {
var username = document.getElementById('<%=TextBoxUserName.ClientID
%>').value;
var password = document.getElementById('<%=TextBoxPassword.ClientID
%>').value;

if (username.search("'") >= 0 || username.search("--") >= 0) // sql


injection characters
{
alert('Please Enter Username');
return false;

}
else
{
if (password.search("'") >= 0 || password.search("--") >= 0)
{
alert('Please Enter Password');

return false;
}
return true;
}

Page | 107
Lab Manual of Fundamentals of Database Systems

}
</script>

Use this link as ref:

http://msdn.microsoft.com/en-us/library/ms161953%28SQL.105%29.aspx
http://msdn.microsoft.com/en-us/library/ff648339.aspx

Post Lab Questions: Create a login page which allows only the administrator to login into website.
Ensure safety against SQL injection.

Page | 108
Lab Manual of Fundamentals of Database Systems

APPENDIX A: LAB EVALUATION CRITERIA

Labs with projects


1. Experiments and their report 50%
a. Experiment 60%
b. Lab report 40%
2. Quizzes (3-4) 15%
3. Final evaluation 35%
a. ProjectImplementation 60%
b. Project report and quiz 40%

Labs without projects


1. Experiments and their report 50%
a. Experiment 60%
b. Lab report 40%
2. Quizzes (3-4) 20%
3. Final Evaluation 30%
i. Experiment 60%
ii. Lab report, pre and post
experiment quiz 40%

Notice:
Copying and plagiarism of lab reports is a serious academic misconduct. First instance of copying
may entail ZERO in that experiment. Second instance of copying may be reported to DC. This may
result in awarding FAIL in the lab course.

Page | 109
Lab Manual of Fundamentals of Database Systems

Appendix B: Safety around Electricity


In all the Electrical Engineering (EE) labs, with an aim to prevent any unforeseen accidents during
conduct of lab experiments, following preventive measures and safe practices shall be adopted:

• Remember that the voltage of the electricity and the available electrical current in EE labs
has enough power to cause death/injury by electrocution. It is around 50V/10 mA that the
“cannot let go” level is reached. “The key to survival is to decrease our exposure to energized
circuits.”
• If a person touches an energized bare wire or faulty equipment while grounded, electricity
will instantly pass through the body to the ground, causing a harmful, potentially fatal, shock.
• Each circuit must be protected by a fuse or circuit breaker that will blow or “trip” when its
safe carrying capacity is surpassed. If a fuse blows or circuit breaker trips repeatedly while in
normal use (not overloaded), check for shorts and other faults in the line or devices. Do not
resume use until the trouble is fixed.
• It is hazardous to overload electrical circuits by using extension cords and multi-plug outlets.
Use extension cords only when necessary and make sure they are heavy enough for the job.
Avoid creating an “octopus” by inserting several plugs into a multi-plug outlet connected to a
single wall outlet. Extension cords should ONLY be used on a temporary basis in situations
where fixed wiring is not feasible.
• Dimmed lights, reduced output from heaters and poor monitor pictures are all symptoms of
an overloaded circuit. Keep the total load at any one time safely below maximum capacity.
• If wires are exposed, they may cause a shock to a person who comes into contact with them.
Cords should not be hung on nails, run over or wrapped around objects, knotted or twisted.
This may break the wire or insulation. Short circuits are usually caused by bare wires
touching due to breakdown of insulation. Electrical tape or any other kind of tape is not
adequate for insulation!
• Electrical cords should be examined visually before use for external defects such as: Fraying
(worn out) and exposed wiring, loose parts, deformed or missing parts, damage to outer
jacket or insulation, evidence of internal damage such as pinched or crushed outer jacket. If
any defects are found the electric cords should be removed from service immediately.
• Pull the plug not the cord. Pulling the cord could break a wire, causing a short circuit.
• Plug your heavy current consuming or any other large appliances into an outlet that is not
shared with other appliances. Do not tamper with fuses as this is a potential fire hazard. Do
not overload circuits as this may cause the wires to heat and ignite insulation or other
combustibles.
• Keep lab equipment properly cleaned and maintained.
• Ensure lamps are free from contact with flammable material. Always use lights bulbs with
the recommended wattage for your lamp and equipment.
• Be aware of the odor of burning plastic or wire.
• ALWAYS follow the manufacturer recommendations when using or installing new lab
equipment. Wiring installations should always be made by a licensed electrician or other
qualified person. All electrical lab equipment should have the label of a testing laboratory.
• Be aware of missing ground prong and outlet cover, pinched wires, damaged casings on
electrical outlets.

Page | 110
Lab Manual of Fundamentals of Database Systems

• Inform Lab engineer / Lab assistant of any failure of safety preventive measures and safe
practices as soon you notice it. Be alert and proceed with caution at all times in the
laboratory.
• Conduct yourself in a responsible manner at all times in the EE Labs.
• Follow all written and verbal instructions carefully. If you do not understand a direction or
part of a procedure, ASK YOUR LAB ENGINEER / LAB ASSISTANT BEFORE
PROCEEDING WITH THE ACTIVITY.
• Never work alone in the laboratory. No student may work in EE Labs without the presence
of the Lab engineer / Lab assistant.
• Perform only those experiments authorized by your teacher. Carefully follow all
instructions, both written and oral. Unauthorized experiments are not allowed.
• Be prepared for your work in the EE Labs. Read all procedures thoroughly before entering
the laboratory. Never fool around in the laboratory. Horseplay, practical jokes, and pranks
are dangerous and prohibited.
• Always work in a well-ventilated area.
• Observe good housekeeping practices. Work areas should be kept clean and tidy at all times.
• Experiments must be personally monitored at all times. Do not wander around the room,
distract other students, startle other students or interfere with the laboratory experiments of
others.
• Dress properly during a laboratory activity. Long hair, dangling jewelry, and loose or baggy
clothing are a hazard in the laboratory. Long hair must be tied back, and dangling jewelry
and baggy clothing must be secured. Shoes must completely cover the foot.
• Know the locations and operating procedures of all safety equipment including fire
extinguisher. Know what to do if there is a fire during a lab period; “Turn off equipment, if
possible and exit EE lab immediately.”

Page | 111
Lab Manual of Fundamentals of Database Systems

Appendix C:Guidelines on Preparing Lab Reports


Each student will maintain a lab notebook for each lab course. He will write a report for each
experiment he performs in his notebook. A format has been developed for writing these lab reports.
Separate formats are devised for hardware and programming stream labs.

Programming Stream Lab Report Format

For programming streams, the format of the report will be as given below:

1. Introduction: Introduce the new constructs/ commands being used, and their significance.
2. Objective: What are the learning goals of the experiment?
3. Design: If applicable, draw the flow chart for the program. How do the new constructs
facilitate achievement of the objectives; if possible, a comparison in terms of efficacy and
computational tractability with the alternate constructs?
4. Issues: The bugs encountered and the way they were removed.
5. Conclusions: What conclusions can be drawn from experiment?
6. Application: Suggest a real world application where this exercise may apply.
7. Answers to post lab questions (if any).

Sample Lab Report for Programming Labs

Introduction

The ability to control the flow of the program, letting it make decisions on what code to execute, is
important to the programmer. The if-else statement allows the programmer to control if a program
enters a section of code or not based on whether a given condition is true or false. If-else statements
control conditional branching.

if ( expression )
statement1
else
statement2

If the value of expression is nonzero, statement1 is executed. If the optional else is present,
statement2 is executed if the value of expression is zero. In this lab, we use this construct to select an
action based upon the user's input, or a predefined parameter.

Page | 112
Lab Manual of Fundamentals of Database Systems

Objective:

To use if-else statements for facilitation of programming objectives: A palindrome is a number or a


text phrase that reads the same backward as forward. For example, each of the following five-digit
integers is a palindrome: 12321, 55555, 45554 and 11611. We have written a C++ program that
reads in a five-digit integer and determines whether it is a palindrome.

Design:

The objective was achieved with the following code:

#include<iostream>

usingnamespacestd;
intmain()
{
inti,temp,d,revrs=0;

cout<<"enter the number to check :";


cin>>i;
temp=i;
while(temp>0)
{
d=temp%10;
temp/=10;
revrs=revrs*10+d;

}
if(revrs==i)
cout<<i<<" is palindorme";
else
cout<<i<<" is not palindrome";

}
}

Screen shots of the output for various inputs are shown in Figure 1:

Page | 113
Lab Manual of Fundamentals of Database Systems

Fig.1. Screen shot of the output

The conditional statement made this implementation possible; without conditional branching, it is
not possible to achieve this objective.

Issues:

Encountered bugs and issues; how were they identified and resolved.

Conclusions:

The output indicates correct execution of the code.

Applications:

If-else statements are a basic construct for programming to handle decisions.

Page | 114

Das könnte Ihnen auch gefallen