DB - LabManual - Withproject - Fall 2019 PDF
DB - LabManual - Withproject - Fall 2019 PDF
Page | 2
Lab Manual of Fundamentals of Database Systems
Table of Contents
Sr. No. Description Page No.
1 List of Equipment 04
Page | 3
Lab Manual of Fundamentals of Database Systems
List of Equipment
Sr. No. Description
1 Workstations (PCs)
Page | 4
Lab Manual of Fundamentals of Database Systems
EXPERIMENT 1
INTRODUCTION TO HTML
Objective
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
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
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
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:
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>
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:
If you click on this link, you will be sent back to the top of the page.
HTML Tables
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
<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
Figure 3
Good Reference:
http://www.w3schools.com
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
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
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
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;
}
.center {text-align:center;}
<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");}
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")};
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>
Figure 2
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:
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
• 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".
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
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
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
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.
Figure 7
Page | 20
Lab Manual of Fundamentals of Database Systems
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
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
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
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)
• 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
• Refresh your database and verify the results from designer on left
Page | 27
Lab Manual of Fundamentals of Database Systems
• Refresh your database and verify the results from designer on the left by expanding Keys
under School table
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)
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
• Select Data from the two tables by running the following commands
Select * from lab4.staff
Select * from lab4.school
Page | 29
Lab Manual of Fundamentals of Database Systems
PostLab Questions
director
did name bestRev
movie
mid mname Directed_by
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
General syntax:
SELECT <list of columns> FROM <table name>
Example:
Select fname, lname, salary, bdate
From employee
General Syntax:
SELECT <* or list of columns>
FROM <table name>
WHERE <condition>
Example:
Select fname, lname, salary, bdate
From employee
Where salary >25000
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
Example:
Select distinct salary
From employee
Example:
Select datediff(yy, bdate,GETDATE())age,
fname from employee
Examples:
select fname, Lname, salary, bdate
from employee
where bdate between '01-Jan-1960' and '31-Dec-1969'
and lname like 'S%'
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
Example:
select e.fname, e.Lname, d.dependent_name
from employee e leftouterjoindependent d on e.ssn=d.essn
orderby e.fname, e.lname
Example:
select e.fname, e.Lname, d.dependent_name
fromdependent d rightouterjoin employee e on e.ssn=d.essn
orderby e.fname, e.lname
Example:
First let us insert a department which doesn’t have a manager yet
insertinto department(Dname, dnumber)values ('Accounts', 10)
Page | 33
Lab Manual of Fundamentals of Database Systems
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
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.
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
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.
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.
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
Page | 37
Lab Manual of Fundamentals of Database Systems
EXERCISE 3:
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.
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
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.
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.
• 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 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.
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
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
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.
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.
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.
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.
Exec getEmployeeDetails
getEmployeeDetails @City='Houston'
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".
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
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
To change the stored procedure and save the updated code you would use the ALTER
PROCEDURE command as follows.
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
4. Modify the above procedure (question 3) to display the salaries of such employees as well as
their names.
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
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.
• 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.
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
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.
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.
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')
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
go
UPDATE TriggerEmployee
SET Name = 'New Name'
WHERE EmployeeID= 2
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.
go
go
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:
Page | 47
Lab Manual of Fundamentals of Database Systems
SELECT COUNT(*)
FROM TriggerEmployee A
) >0
BEGIN
PRINT 'CAN NOT BE deleted'
END
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.
To fire the trigger we can try to drop any table of the database on which trigger was defined.
DROP TABLE TriggerEmployee
go
go
To fire the trigger we can try to alter any table of the database on which trigger was defined.
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
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
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)
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).
ERwin will now display the main window from which most of your ER diagram development will
be done, as shown in Figure 3.
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.
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.
At this point, you may wish to save and name your diagram to avoid loss should the system or
application crash.
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
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
Make another entity, DEPARTMET with primary key dept_id and attributes name and city shown in
the Figure 8 below.
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.
• 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
Page | 56
Lab Manual of Fundamentals of Database Systems
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
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
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.
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
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 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
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
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.
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.
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
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)
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
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
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
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>
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
• 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>
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
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
Figure 21
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
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
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
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
• Familiarize you with Delete through Grid View and Insert via ASP.net web form.
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;
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;
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
{
}
//////////////////////////////////////////////////////
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
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
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
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
<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 :
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());
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.
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
LoadGrid();
}
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
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
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
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
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 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>
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
Figure 1
When clicked on Buy it of first row, the ShoppingPage.aspx look like thisas shown in figure 2.
Figure 2
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
Figure 7
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.
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:
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:
This is all fine if the data is valid, but what if the user types something
unexpected? What happens if the user types:
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.
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.
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
<script type="text/javascript">
function validation() {
var username = document.getElementById('<%=TextBoxUserName.ClientID
%>').value;
var password = document.getElementById('<%=TextBoxPassword.ClientID
%>').value;
}
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>
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
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
• 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
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).
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:
Design:
#include<iostream>
usingnamespacestd;
intmain()
{
inti,temp,d,revrs=0;
}
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
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:
Applications:
Page | 114