0% found this document useful (0 votes)
27 views78 pages

DBMS R-2021

The document is a laboratory notebook for the Database Management Systems course at Bethlahem Institute of Engineering, detailing various SQL commands and experiments. It includes sections on Data Definition Language (DDL), Data Manipulation Language (DML), views, joins, and other database concepts, along with example queries and outputs. The notebook serves as a record of practical work done by students during the academic year 2022-2023.

Uploaded by

examcell9615
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
27 views78 pages

DBMS R-2021

The document is a laboratory notebook for the Database Management Systems course at Bethlahem Institute of Engineering, detailing various SQL commands and experiments. It includes sections on Data Definition Language (DDL), Data Manipulation Language (DML), views, joins, and other database concepts, along with example queries and outputs. The notebook serves as a record of practical work done by students during the academic year 2022-2023.

Uploaded by

examcell9615
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 78

BETHLAHEM INSTITUTE OF ENGINEERING

KARUNGAL- 629 157


Kanyakumari District

LABORATORY NOTE BOOK

DATABASE MANAGEMENT SYSTEMS


LABORATORY

NAME :……………………………………..

REG NO :……………………………………..

BRANCH :……………………………………..

SEM/YEAR :……………………………………..

1
BETHLAHEM INSTITUTE OF ENGINEERING
KARUNGAL- 629 157
Kanyakumari District

DEPARTMENT OF…………………………………………………..

LABORATORY RECORD NOTE BOOK

2022 - 2023
This is to certify that this is the bonafide record of the work done by Mr./Ms.

……………………………………Register Number ……………………………….…Of the year …………….

B.E. / B.Tech., Department of…………………………….…………in the ………………………………….

Laboratory in the …………………………..Semester

Staff-in-charge Head of the Department

University Examination held on……………………………………………………………

Internal Examiner External Examiner

2
CONTENTS

EX.NO DATE NAME OF THE EXPERIMENT PAGE.NO SIGNATURE

DATA DEFINITION LANGUAGE (DDL)


COMMANDS
1
[TABLE CREATION]

DATA MANIPULATION LANGUAGE


2 (DML) COMMANDS

VIEWS
3

JOINS
4

CONSTRAINTS
5

NESTED QUERIES
6

PROCEDURES
7

8 TRIGGER

FUNCTION
9

CREATE DATABASE USING XML


10

DOCUMENT,COLUMN AND GRAPH


11 BASED DATABASE USING NOSQL

LIBRARY MANAGEMENT SYSTEM


12

RAILWAY RESERVATION
13 MANAGEMENT

14 COP FRIENDLY APP-Eseva

3
DATA DEFINITION LANGUAGE (DDL) COMMANDS

[TABLE CREATION]

Ex.No: 1
Date:

Aim
To create a database and write SQL queries to retrieve information from the database.

DDL COMMANDS
Data definition language is used to create a table, alter the structure of table and drop the table.

 CREATE
 ALTER
 RENAME
 DROP
 TRUNCATE

CREATE Command
It is used to create a table with attributes specified.
Syntax :
create table tablename(field1 datatype(size), field2 datatype(size),…., fieldn datatype(size));

ALTER Command
This query alters the table with new attribute specified.

Syntax:
alter table tablename add (fieldname datatype(size));

DROP Command
To drop the table along with the schema of the table ie, delete the contents of the table as well the
structure.

Syntax:
drop table tablename;
RENAME Command
To change the name of the table.
Syntax:
rename <old name> to <new name>

TRUNCATE Command
It is used to delete the records (values) in the table but the structure of table remains there.
Syntax:

4
truncate table tablename;

SELECT Command
It is used to display the data.
Syntax :
select * from tablename;

SP_HELP Command
It is used to view the table structure.
Syntax :
sp_help tablename;

INSERT Command
It is used to insert the field values into the table.
Syntax :
insert into tablename values(field1, field2, ….,fieldn);

Programs and Queries

Table creation
create table customer_details (name varchar(20), age int, address varchar(20), id int, salary char(10));

output
Table Created.

Inserting values

insert into customer_details values('Jeni', 19, 'karungal',209,2000);


insert into customer_details values('Suji', 16, 'marthandam',123,22000);
insert into customer_details values('Anusha', 11, 'arumanai',145,9000);
insert into customer_details values('Shiya', 10, 'melpuram',122,23000);
insert into customer_details values('Aarick', 9, 'Chennai',169,28000);
output

(1 row(s) affected)

(1 row(s) affected)

(1 row(s) affected)

(1 row(s) affected)

(1 row(s) affected)

To View Table

select * from customer_details;

5
output

Alter Table
alter table customer_details add department varchar(10);

output

Command(s) completed successfully.

select * from customer_details;

insert into customer_details values('Dio', 14, 'selam',133,38000,'IT');

output

(1 row(s) affected)

select * from customer_details;

Truncate Table
truncate table customer_details;

output

6
Command(s) completed successfully.

select * from customer_details;

Drop Table
drop table customer_details;

output

Command(s) completed successfully.

select * from customer_details;

Msg 208, Level 16, State 1, Line 1


Invalid object name 'customer_details'. [Because there is no table with tablename 'customer_details']

Result
Thus the DDL commands were used sucessfully.

DATA MANIPULATION LANGUAGE (DML) COMMANDS

7
Ex.No: 2
Date:

Aim
To perform insertion, deletion, modifying, altering, updating, and viewing record based on
conditions.

DML COMMANDS
DML commands allow the user to manipulate the data in database.

 SELECT
 INSERT
 DELETE
 UPDATE

INSERT Command
It is used to insert the values in the database.
Syntax:
insert into tablename values(field1, field2, …, fieldn);

SELECT Command
It is used to select the objects from the database.
Syntax:
Select * from <tablename>;

DELETE Command
It is used to delete the records from the table.
Syntax:
Delete <tablename> where <column name>=value;

UPDATE Command

It is used to update the records in the table.


Syntax:
Update tablename set <column name>=value where <column name>=<value>;

Programs and Queries

Table creation
create table bank_details (name varchar(20), city varchar(20),account_num int,amount money)

output

8
Command(s) completed successfully.

Insert values

insert into bank_details values('shibin', 'marthandam',2222,350000)


insert into bank_details values('Ribin', 'kollam',2333,250000)
insert into bank_details values('shabin', 'mumbai',3222,120000)
insert into bank_details values('Bibin', 'Arumanai',2323,220000)
insert into bank_details values('Jino', 'Chennai',2121,110000)

output

(1 row(s) affected)

(1 row(s) affected)

(1 row(s) affected)

(1 row(s) affected)

(1 row(s) affected)

select * from bank_details;

Update Command

update bank_details set city='Nagercoil' where name='Bibin';

output

(1 row(s) affected)

select * from bank_details;

9
Select Command

select name,city from bank_details;

Delete Command

delete from bank_details where name='jino';

output

(1 row(s) affected)

select * from bank_details;

Like Command

select name,account_num from bank_details where name like'_i%'or name like's%';

Ordering the display of tuples

10
select name , city from bank_details order by city;

Aggregate Functions
These functions take a collection of values as input and return a single value.

 Avg: Returns average value of n.


 Min: Return minimum value of expression.
 Max: Returns maximum value of expression.
 Sum: Returns sum of values of n.
 Count: Returns the number of rows.

Output

select avg(amount)"Average amount" from bank_details;

select min(amount)"Average amount" from bank_details;

select max(amount)"Average amount" from bank_details;

select sum(amount)"Average amount" from bank_details;

Result
Thus the DML commands are executed successfully.

11
VIEWS AND DCL COMMANDS

Ex.No: 3
Date:

Aim
To execute and verify the SQL commands for views.

Procedure

Step 1: Start
Step 2: Create the table with its essential attributes
Step 3: Insert attribute values into the table.
Step 4: Create the view from the above created table.
Step 5: Execute different commands and extract information from the view.
Step 6: Stop

Definition
 View is a table which is a subset of actual table.
 View is an object that gives the user a logical view of data from an underlying table.
 You can restrict users can view by allowing them to see only a few attributes from the table.

Uses

 Views help to encapsulate complex query and make it reusable.


 Provides user security on each view – it depends on your data policy security.
 View used to convert units – if you have a financial data in US currency, you can create view to
convert them into Euro for viewing in Euro currency.

Creation of views
Syntax: create view viewname as select columnname1, columnname2
from tablename where columnname = “fieldname”

Update View
Syntax: update viewname set columnname=’field’ where
columnname = “field”

Truncate Command
It is used to delete the records(values) but return the structure.
Syntax : truncate table tablename;
Drop Command
It is used to delete contents as well as the structure.
Syntax : drop table tablename;

Programs and Queries

12
Table creation
create table student_info(stud_name varchar(10),stud_regno int,sex varchar(10),year char(10),college
varchar(25));

output

Command(s) completed successfully.

Insert values
insert into student_info values('jeni', 10905,'female','first','vins');
insert into student_info values('Joshna', 30904,'female','fourth','st.Xavier');

insert into student_info values('Riya', 50890,'female','second','Bethlahem');


insert into student_info values('Gerom', 39875,'male','first','Noorul Islam');

insert into student_info values('Shan', 29042,'male','first','SRM');


insert into student_info values('Shali', 89765,'female','third','Bethlahem');

output

(1 row(s) affected)

(1 row(s) affected)

(1 row(s) affected)

(1 row(s) affected)

(1 row(s) affected)

(1 row(s) affected)

Select * From student_info;

View Creation
create view student1 as select * from student_info where year='first';

output
Command(s) completed successfully.

13
select * from student1;

Update view
update student1 set stud_name='Kanika' where stud_regno=10905;

output
(1 row(s) affected)

select * from student1;

Rename the column

create view student2 as select stud_name as sname,stud_regno as regno,sex as gender,year as year,college


as college_name from student_info where year='first';

output
Command(s) completed successfully.

select * from student2;

Drop
drop view student1;
output
Command(s) completed successfully.

Dcl Commands:
---transactions
--roll back
---execute the below querries together

begin tran
select * from students;
delete from students where s_name = 'john';

14
select * from students;
rollback;
select * from students;

--commit
---execute the below querries together

begin tran
select * from students;
delete from students where s_name = 'john';
select * from students;
commit;
select * from students;
rollback;
select * from students;

insert into students values(5,'john','pathiramangalam',5);

--saving a transaction
---execute the below querries together

begin transaction tran1;


select * from students;
delete from students where s_name = 'john';
select * from students;
save transaction tran1;

15
--execute twice
--then note down the output

select * from students;


rollback transaction tran1;
select * from students;

Result
Thus the SQL commands for view and DCL has been verified and executed successfully.

16
JOINS

Ex.No: 4
Date:

Aim
To write and execute the queries for join.

Definition
Join is a query in which data is retrieved from two or more tables. A join matches data from two or
more tables, based on the values of one or more columns in each table.

Types

Different types of join are:

 Inner join
 Outer join
 Natural join

Inner Join
Inner join returns the matching rows from the tables that are being joined.

Outer Join
- Extended form of the inner join
- Rows in one table having no matching rows in the other table will also appear in the result table
with nulls.
Types:

 Left outer
 Right outer
 Full outer

Left Outer Join: Returns matching rows from the tables being joined and also non-matching rows from
the left table in the result and places null values in the attributes that come from the right table.

Right Outer Join: Returns matching rows from the tables being joined and also non-matching rows from
the right table in the result and places null values in the attributes that come from the left table.

Full Outer Join: It pads tuples from the left relation that did not match with any tuple from the right
relation, as well as tuples from the right relation that did not match with any tuple from the left relation
and adds them to the resultant relation.

Programs And Queries

17
create table marks_details(name varchar(20),m1 int, m2 int,m3 int);

output
Command(s) completed successfully.

insert into marks_details values('revathy',67,89,50);


insert into marks_details values('Archana',89,76,54);
insert into marks_details values('Monisha',78,69,90);
insert into marks_details values('Leena',71,74,77);
insert into marks_details values('Marry',77,88,99);

output

(1 row(s) affected)

(1 row(s) affected)

(1 row(s) affected)

(1 row(s) affected)

(1 row(s) affected)

select * from marks_details;

create table student_detail(name varchar(20),age int,address varchar(20));

output
Command(s) completed successfully.

insert into student_detail values('Shan', 23,'marthandam');


insert into student_detail values('Monisha', 21,'Karungal');
insert into student_detail values('Archana', 22,'Arumanai');
insert into student_detail values('Revathy', 23,'Karakonam');
insert into student_detail values('Dio', 24,'Trichy');

output

(1 row(s) affected)

18
(1 row(s) affected)

(1 row(s) affected)

(1 row(s) affected)

(1 row(s) affected)

select * from student_detail;

Left Outer Join

Select marks_details.name,marks_details.m1,marks_details.m2,marks_details.m3,
student_detail.address from marks_details left outer join student_detail on
marks_details.name=student_detail.name;

output

Right Outer Join

Select marks_details.name,marks_details.m1,marks_details.m2,marks_details.m3,
student_detail.address ,student_detail.age from marks_details right outer join student_detail on
marks_details.name=student_detail.name;

output

19
Full Outer Join

select marks_details.name,marks_details.m1,marks_details.m2,marks_details.m3, student_detail.address


,student_detail.age from marks_details full outer join student_detail on
marks_details.name=student_detail.name;

output

Union and Intersection


These operations takes two relations as input and produces one relation as output.

Condition: Two relations must contain the same number of columns.

create table student_list1(name varchar(20),year varchar(7),dept varchar(5));

output
Command(s) completed successfully.

insert into student_list1 values('Nisha','fourth','IT');


insert into student_list1 values('Shyba','fourth','IT');
insert into student_list1 values('Auxilia','fourth','CSE');
insert into student_list1 values('Sheena John','fourth','IT');
insert into student_list1 values('Bijimol','third','IT');
output

20
(1 row(s) affected)

(1 row(s) affected)

(1 row(s) affected)

(1 row(s) affected)

(1 row(s) affected)

select * from student_list1;

create table student_list2(name varchar(20),year varchar(7),dept varchar(5));

output
Command(s) completed successfully.

insert into student_list2 values('Nisha','fourth','IT');


insert into student_list2 values('Rini','third','ECE');
insert into student_list2 values('Sumi','second','EEE');
insert into student_list2 values('Sheena John','fourth','IT');
insert into student_list2 values('Chithra','third','IT');

output

(1 row(s) affected)

(1 row(s) affected)

(1 row(s) affected)

(1 row(s) affected)

(1 row(s) affected)

21
select * from student_list2;

i) Union
It includes all the tuples from both the relation.

select name,year,dept from student_list1 union select name,year,dept from student_list2;

ii) Intersection
It includes all the tuples that are same in both the relation.

select name,year,dept from student_list1 intersect select name,year,dept from student_list2;

Result
Thus the queries of join has been verified and executed successfully.

22
CONSTRAINTS

Ex.No: 5
Date:

Aim
To execute and verify the constraints in Data Definition Language Commands.

Definition
Constraints are part of the table definition that limits a restriction on the value entered into its
column.

Types of Constraint
 Primary Key
 Foreign Key / Reference
 Check
 Unique
 Not Null
 Null
 Default

 Primary Key
- Primary key is used to uniquely identify each row in the table.
- Primary Key value must not be null and must be unique across the column.

 Check Constraint
- Check Constraint defines a condition that every row must satisfy.

 Unique Constraint
- Unique Key is used to ensure that the information in the column for each record is unique.

 Not Null Constraint


- It is used to enforce that the particular column will not accept null values.

 Null Constraint
- While creating tables, if a row lacks a data value for a particular column, that value is said to be
null.
- Columns of any data types may contain null values unless the column was defined as not null
when the table was created.

 Foreign Key Constraint


- Foreign Key represents relationship between tables.

23
- The table with foreign key is related to the primary key table from which the foreign key is
derived.

Programs and Queries

create table employees(empno int primary key, empname varchar(20),job varchar(20),salary int,dept_no
int);

output
Command(s) completed successfully.

insert into employees values(23,'Abilash','Professor',20000,4);


insert into employees values(45,'Renin','Asst Professor',18000,5);
insert into employees values(34,'Sherin','Professor',22000,4);
insert into employees values(65,'Ajay','Asso Professor',24000,9);
insert into employees values(71,'Anurag','Asst Professor',22000,3);

output

(1 row(s) affected)

(1 row(s) affected)

(1 row(s) affected)

(1 row(s) affected)

(1 row(s) affected)

Select * from employees;

Primary Key

insert into employees values(71,'Vibin','Asst Professor',12000,6);

24
output

Msg 2627, Level 14, State 1, Line 1


Violation of PRIMARY KEY constraint 'PK__employees__4336F4B9'. Cannot insert duplicate key in
object 'dbo.employees'.
The statement has been terminated.

Reason: We inserted same empno in 2 records. It can’t accept because empno is set as primary Key. The
value of primary Key must be unique.

Null Constraint
We are already created one table. Now if we want to add one attribute in the previous table , the
command is.,

alter table employees add address varchar(20);

output
Command(s) completed successfully.

Select * from employees;

The table is displayed and the address fields for previous records are displayed as null.

insert into employees values(61,'Vibin','Asst Professor',12000,6,'Chennai');

output

(1 row(s) affected)

Select * from employees;

25
Check Constraint

alter table employees add check(salary > 10000)

output
Command(s) completed successfully.

insert into employees values(33,'Arun','AsstProfessor',8000,5,'Coimbatore');

output
The INSERT statement conflicted with the CHECK constraint "CK__employees__salar__442B18F2".
The conflict occurred in database "master", table "dbo.employees", column 'salary'.
The statement has been terminated.

Reason: We set as, the salary should be greater than 10000 but we entered the salary is 8000, so it can’t
accept.

Not Null Constraint

insert into employees values(33,'Asst Professor',28000,5,'Coimbatore');

output
Insert Error: Column name or number of supplied values does not match table definition.

Reason: The empname is missed and it can’t be null.

Unique Constraint

create table employees1(empno int primary key, empname varchar(20),job varchar(20) unique,salary
int,dept_no int);

output
Command(s) completed successfully.
insert into employees1 values(45,'Shyja','Asst Professor',28000,5);
insert into employees1 values(55,'Karthika','Professor',32000,9);

output

26
(1 row(s) affected)

(1 row(s) affected)

Select * from employees1;

insert into employees1 values(22,'Adlin','Professor',32000,9);

output
Violation of UNIQUE KEY constraint 'UQ__employees1__47FBA9D6'. Cannot insert duplicate key in
object 'dbo.employees1'.
The statement has been terminated.

Reason:The job must be unique but we entered as same job(professor) for Adlin.

Foreign Key Constraint

create table employees2(empno int foreign key references employees1,emp_address varchar(20));

output
Command(s) completed successfully.

insert into employees2 values(45,'Chennai');


insert into employees2 values(55,'Trichy');

output

(1 row(s) affected)

(1 row(s) affected)

Select * from employees2;

insert into employees2 values(33,'Mumbai');

27
output
The INSERT statement conflicted with the FOREIGN KEY constraint
"FK__employees__empno__49E3F248". The conflict occurred in database "master", table
"dbo.employees1", column 'empno'.
The statement has been terminated.

Reason: The empno should be same in both the relation ie, employees1 and employees2. But we entered
empno as 33, that is not in employees1 so it can’t accept in employees2.

Result
Thus the queries for constraints has been verified and executed successfully.

28
NESTED QUERIES

Ex.No: 6
Date:

Aim
To execute and verify the SQL Commands for Nested Queries.

Definition
 Nested Query can have more than one level of nesting in a single query.
 A subquery is a select from where expression that is nested within another query.
 Subqueries are used to perform tests for set membership to make set comparisons and determine
set cardinality.

Set Memberships

 IN : The set is a collection of values produced by a select clause.


 NOT IN : For the absence of set membership.

Set Comparison
SQL uses various comparison operators such as <, <=,>, >=, =, <> , any, all and some , etc to
compare sets.

Programs and Queries

create table book1(bname varchar(10),title varchar(10),pubyear int, price money, authorname


varchar(10),pubname varchar(10));

output
Command(s) completed successfully.

insert into book1 values('oops','classes',2004,600,'Desikan','Charulatha')


insert into book1 values('os','schedular',2005,900,'velu','kins')
insert into book1 values('DBMS','Queries',2001,670,'Seema','Technical')
insert into book1 values('ST','BlachBox',2002,658,'srinivasan','Pearson')
insert into book1 values('SE','Design',2008,467,'Logan','Lekshmi')

output

(1 row(s) affected)

(1 row(s) affected)

(1 row(s) affected)

(1 row(s) affected)

29
(1 row(s) affected)

Select * From book1;

create table author(authorname varchar(10), country varchar(15))

output
Command(s) completed successfully.

insert into author values('Desikan','Mumbai')


insert into author values('velu','India')
insert into author values('Seema','China')
insert into author values('srinivasan','Australia')
insert into author values('Logan','London')

output

(1 row(s) affected)

(1 row(s) affected)

(1 row(s) affected)

(1 row(s) affected)

(1 row(s) affected)

select * from author;

create table publisher(pubname varchar(10), State varchar(15))

30
output
Command(s) completed successfully.

insert into publisher values('Charulatha','Mumbai')


insert into publisher values('kins','Mumbai')
insert into publisher values('Technical','Mumbai')
insert into publisher values('Pearson','Mumbai')
insert into publisher values('Lekshmi','Mumbai')

output

(1 row(s) affected)

(1 row(s) affected)

(1 row(s) affected)

(1 row(s) affected)

(1 row(s) affected)

select * from publisher;

IN:

select title,authorname,pubname,pubyear from book1 where pubyear in (2005,2001,2002);

select * from author where authorname in (select authorname from book1 where pubyear='2008');

31
NOT IN:

select title,authorname,pubyear from book1 where pubyear not in (2005,2001);

select title from book1 where authorname not in(select authorname from author where country
='Australia');

SET COMPARISON:

select title from book1 where price > all (select price from book where pubyear='2004')

TEST FOR EMPTY RELATION

select title from book1 where exists (select * from author where book1.authorname=author.authorname)

Result
Thus the above commands are executed and the output was verified successfully.

32
PROCEDURES
Ex.No: 7
Date:

Aim

To create a parameter for swapping two number and list down the table details.

Procedure definition
A procedure is a subprogram that performs a specific action. The syntax for creating a procedure
is given below:

create or replace procedure<proc_name>[prameter list]is


<local declaration>
begin
(executable statements)
[exception](exception handlers)
end;

A procedure has two parts:


 Specification
 Body

Syntax to execute a procedure


Exec<procedure name> parameters;

Programs and Queries

create table book(isbn int, book_nam varchar(25),qty int);


insert into book values(1,'os',10);
insert into book values(2,'se',11);
insert into book values(3,'dbms',13);
insert into book values(4,'coa',15);
insert into book values(5,'pqt',17);
select * from book;

Output

33
Procedure for update

create procedure updatebook(@ip1 int,@ip2 int)


as
begin
update book set qty=qty*@ip1 where isbn=@ip2;
end
exec updatebook 10,2;
select * from book;

output

Procedure for Alter

alter procedure updatebook(@ip1 int,@ip2 int)


as
begin
update book set qty=qty+@ip1 where isbn=@ip2;
end
exec updatebook 5,3;
select * from book;

output

Survive the details of birthday using procedure

create procedure survivaldetails(@part varchar(10),@birthday datetime)


as

34
begin
declare @output int;
if(@part='day')
begin
set @output=datediff(day,@birthday,getdate());
print 'you have survived'+convert(varchar(20),@output)+'days';
end
else if(@part='month')
begin
set @output=datediff(month,@birthday,getdate());
print'you have survived'+convert(varchar(20),@output)+'months';
end
else
begin
set @output=datediff(year,@birthday,getdate());
print'you have survived'+convert(varchar(20),@output)+'years';
end
end

exec survivaldetails 'day','10-29-1998';


exec survivaldetails 'month','10-29-1998';
exec survivaldetails 'year','10-29-1998';

output

Result
Thus the parameter for swapping two numbers are executed and the output was verified
sucessfully.

35
TRIGGER

Ex.No: 8
Date :

Aim
To implement the program using trigger.

Trigger Definition
A trigger is a statement that the system executes automatically as a side effect of a modification
to the database.
To design a trigger,
specify when a trigger is to executed.
Specify the actions to be taken when the trigger executes.
Example
Suppose a warehouse wishes to maintain a minimum inventory of each item. When the inventory
level of an item falls below the minimum level, an order should be placed automatically.

Program

create table books(isbn int primary key,title char(15),author varchar(15),qty_instock int,price


money,pub_year int);
create table customers (cust_id int primary key,cust_name char(15),address varchar(20),card_no int);
create table orders(order_no int primary key,cust_id int,order_date datetime foreign key(cust_id)
references customers);
create table order_list(order_no int,isbn int,qty int,ship_date datetime primary key(order_no,isbn),foreign
key(isbn) references books,foreign key(order_no) references orders);
create table stock (isbn int,stock_qty int,recorderlevel int,recorderqty int);

insert into books values(1,'dbms','navathe',50,200,1985);


insert into books values(2,'pqt','nathan',50,210,1987);
insert into books values(3,'coa','nave',50,200,1985);
insert into books values(4,'daa','raja',50,175,2000);

insert into customers values(1,'gifty','pathiramangalam',1);


insert into customers values(2,'brilly','pathiramangalam',2);
insert into customers values(3,'john','pathiramangalam',3);
insert into customers values(4,'joy','pathiramangalam',4);

insert into orders values(1,1,'2-12-1984')


insert into orders values(2,3,'2-12-1984')
insert into orders values(3,2,'2-12-1984')
insert into orders values(4,4,'2-12-1984')
insert into orders values(5,4,'2-12-1986')
insert into orders values(6,4,'2-12-1986')

insert into order_list values(1,3,50,'4-03-2012');


insert into order_list values(2,1,50,'5-03-2012');
insert into order_list values(3,2,50,'4-03-2012');
insert into order_list values(4,4,43,'6-03-2012');

36
insert into stock values(4,56,60,200);
insert into stock values(3,53,65,200);
insert into stock values(2,55,60,200);
insert into stock values(1,55,60,200);

create trigger trigger1 on order_list


after insert
as
begin
declare @qty int,@ord_qty int,@ord_no int;
declare @isbn int;
if(@@rowcount>0)
begin
declare isbn_cursor scroll cursor for
select isbn from stock;
open isbn_cursor;
fetch last from isbn_cursor into @isbn;
select @qty = stock_qty from stock where isbn = @isbn;
close isbn_cursor;
deallocate isbn_cursor;
declare ordno_cursor scroll cursor for
select order_no from order_list;
open ordno_cursor;
fetch last from ordno_cursor into @ord_no;
select @ord_qty = qty from order_list where order_no = @ord_no;
close ordno_cursor;
deallocate ordno_cursor;
if(@qty<@ord_qty)
begin
delete from order_list where order_no = @ord_no;
print'ordered quality not available';
end
end
end

select * from books;


select * from orders;
select * from order_list;
select * from stock;

Output

Table : Books

37
Table : Orders

Table: Order_list

Table: Stock

Execute this statement :


insert into order_list values(6,1,60,'03-02-2012');

output
(1 row(s) affected)
ordered quantity not available

(1 row(s) affected)

[Reason:isbn=1, the book is dbms, its qty_instock is only 50 but we order for 60 books]
This order cannot insert into order_list. It is deleted automaticaaly.

Execute this statement :


insert into order_list values(6,1,50,'03-02-2012');

output
(1 row(s) affected)

38
[This order is inserted into the order_list. The stock is 50 also we ordered for 50]

Result
Thus the trigger procedure has been executed sucessfully and the output was verified.

39
FUNCTION

Ex.No: 9
Date :

Aim
To write a functional procedure to find out the months,year and days you survived.

Function Definition
A function is a subprogram that computes a value.(It returns a single value.)
Function are similar to procedure but the difference is procedure should not return any value
but the function returns a value.

Syntax
create function <function name> [argument list] return datatype
(local declaration)
begin
(executable statements)
[exception]
(exception handler)
end;

Program

create function sp_datediff(@ip datetime) returns int


as
begin
declare @lifespan int;
select @lifespan = datediff(month,@ip,getdate());
return @lifespan;
end

select dbo.sp_datediff('01-28-1984')

Output

For month

For days

(change to days and year in place of month)

alter function sp_datediff(@ip datetime) returns int


as

40
begin
declare @lifespan int;
select @lifespan = datediff(day,@ip,getdate());
return @lifespan;
end

select dbo.sp_datediff('01-28-1984')

Output

Days Year

Result

Thus the function for days survived was executed and the output was verified successfully.

41
Ex.No:10 CREATE DATABASE USING XML

Date :

AIM:

To create an XML database and validate it using XML schema.

STEPS:

 Create an XML document and save as student.xml.


 Create a XSD(XML Schema Definition) and link to the XML document .
 Perform validation by using a XSD.

Student.XML

<?xml version="1.0" encoding="UTF-8"?>

<students xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xsi:noNamespaceSchemaLocation="./student_db.xsd" school="Bethlahem Matric School">

<student id="101">

<rollno>101</rollno>

<name>John Doe</name>

<class>10th</class>

<marks>

<subject>Mathematics</subject>

<score>90</score>

</marks>

<marks>

<subject>Science</subject>

<score>85</score>

</marks>

<marks>

42
<subject>English</subject>

<score>95</score>

</marks>

<marks>

<subject>History</subject>

<score>80</score>

</marks>

<marks>

<subject>Geography</subject>

<score>75</score>

</marks>

</student>

<student id="102">

<rollno>102</rollno>

<name>Jane Smith</name>

<class>12th</class>

<marks>

<subject>Mathematics</subject>

<score>92</score>

</marks>

<marks>

<subject>Biology</subject>

<score>89</score>

</marks>

<marks>

<subject>Physics</subject>

43
<score>87</score>

</marks>

<marks>

<subject>Chemistry</subject>

<score>85</score>

</marks>

<marks>

<subject>English</subject>

<score>90</score>

</marks>

</student>

</students>

Student_db.xsd

<?xml version="1.0" encoding="UTF-8"?>

<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">

<xs:element name="students">

<xs:complexType>

<xs:sequence>

<xs:element name="student" maxOccurs="unbounded">

<xs:complexType>

<xs:sequence>

<xs:element name="rollno" type="xs:integer" />

<xs:element name="name" type="xs:string" />

<xs:element name="class" type="xs:string" />

<xs:element name="marks" minOccurs="5" maxOccurs="5">

<xs:complexType>

44
<xs:sequence>

<xs:element name="subject" type="xs:string" />

<xs:element name="score" type="xs:integer" />

</xs:sequence>

<xs:attribute name="weightage" type="xs:integer" default="100" />

<xs:attribute name="remark" type="xs:string" use="optional" />

</xs:complexType>

</xs:element>

</xs:sequence>

<xs:attribute name="id" type="xs:string" use="required" />

</xs:complexType>

</xs:element>

</xs:sequence>

<xs:attribute name="school" type="xs:string" use="required" />

</xs:complexType>

</xs:element>

</xs:schema>

Result:

Thus the XML database is created and validated using XML schema

45
Ex.No:11 DOCUMENT,COLUMN AND GRAPH BASED DATABASE USING NOSQL

Date:

Aim:

To create document, column and graph based data using NOSQL database tools.

Procedure:

Create a Database and Collection

Once you connect to your deployment using MongoDB for VS code, use the left navigation to:

1. Select an active connection and click the + icon that appears.

2. A MongoDB playground automatically opens with a template form to create a database and a
regular collection or a time series collection.

3. Fill in const database and const collection with names of your database and collection.

4. Uncomment the form of the collection you wish to create.

5. Fill in the collection fields according to your collection's specifications.

6. To run the playground, click the Play Button at the top right of the VS code navigation bar.

Code:

use('friends');

db.persons.drop();

db.friends.drop();

db.createCollection('persons');

db.createCollection('friends');

db.persons.insertMany([

46
{ _id: 'john', name: 'John' },

{ _id: 'jane', name: 'Jane' },

{ _id: 'joe', name: 'Joe' },

{ _id: 'jim', name: 'Jim' },

{ _id: 'jill', name: 'Jill' },

{ _id: 'jack', name: 'Jack' },

{ _id: 'james', name: 'James' },

]);

db.friends.insertMany([

{ _id: 'friend_1', personId: 'john', friendId: 'jane' },

{ _id: 'friend_2', personId: 'john', friendId: 'joe' },

{ _id: 'friend_3', personId: 'jane', friendId: 'jim' },

{ _id: 'friend_4', personId: 'jane', friendId: 'jill' },

{ _id: 'friend_5', personId: 'joe', friendId: 'jack' },

{ _id: 'friend_6', personId: 'jim', friendId: 'jack' },

{ _id: 'friend_7', personId: 'jill', friendId: 'jack' },

]);

// Find degree of separation between two persons

const person1 = 'john';

const person2 = 'jack';

const result = db.friends.aggregate([

47
$match: {

personId: person1,

},

$graphLookup: {

from: "friends",

startWith: "$friendId",

connectFromField: "friendId",

connectToField: "personId",

maxDepth: 2,

depthField: "depth",

as: "connections"

},

$set: {

degrees: {

$map: {

input: {

$filter: {

input: "$connections",

as: "conn",

cond: { $eq: ["$$conn.friendId", person2]}

},

48
as: "friends",

in: {

$sum: [

{ $toInt: "$$friends.depth" },

},

$set: {

degrees: {

$cond: [

{ $eq : ["$friendId", person2]},

{ $concatArrays: [[1], "$degrees"]},

"$degrees"

},

$unwind: "$degrees"

},

49
$group: {

_id: "$personId",

degrees: {

$min: "$degrees"

},

$project: {

_id: 0,

degrees: 1

]);

const degrees = result.next()?.degrees ?? null;

if (degrees) {

print(`The degree of separation between ${person1} and ${person2} is ${degrees}`);

} else {

print(`There is no connection between ${person1} and ${person2}`);

Output:

The degree of separation between john and jack is 2 .

Result:

Thus the document, column and graph based data created using NOSQL database tools

LIBRARY MANAGEMENT SYSTEM


Ex.No:12

50
Date :

Aim
To implement library management system.

Procedure

STEP 1: Create a new form

STEP 2: Place the label box and change their properties

STEP 3: Place the textbox for the labels

STEP 4: Place the command button and change their properties caption and name

STEP 5: Insert the data control

Select Add Ins -> Visual Data Manager

Select File->New->Microsoft access->version 7.0 MDB..

Give a table name and click save

In the pop-up window right click properties and select new table.

Give the table name, Using Add field add the required fields

In our example Tile – Text, Author-Text, Book No – Integer

Click ok -> Build table

STEP 6: Select the Data control and change their property as

Connect: access

Database name: (Path of the table created (eg: C:\table)

Record Source: Database name

STEP 7: Select the textbox and change its properties

1. Data field [eg: Text1 : Datafield=Title]


2. Data source [eg. Text1: Datasource=data1]
STEP 8: Write the code for the required controls

EXECUTION CODE:

Private Sub Add_Click()

Data1.Recordset.AddNew

End Sub

51
Private Sub clear_Click()

Text1.Text = ""

Text2.Text = ""

Text3.Text = ""

End Sub

Private Sub delete_Click()

Data1.Recordset.delete

End Sub

Private Sub edit_Click()

Data1.Recordset.edit

End Sub

Private Sub exit_Click()

End

End Sub

Private Sub first_Click()

Data1.Recordset.MoveFirst

End Sub

Private Sub last_Click()

Data1.Recordset.MoveLast

End Sub

Private Sub next_Click()

52
If (Data1.Recordset.EOF) Then

Data1.Recordset.MoveLast

Else

Data1.Recordset.MovePrevious

End If

End Sub

Private Sub previous_Click()

If (Data1.Recordset.BOF) Then

Data1.Recordset.MovePrevious

Else

Data1.Recordset.MoveLast

End If

End Sub

FORM DESIGN

OUTPUT

53
RESULT

Thus library management system is implemented successfully.

RAILWAY RESERVATION MANAGEMENT

Ex. No: 13
Date:

54
Aim

To create a VB.NET windows form application for Railway Reservation Management.

Backend Part

create database railway

use railway

-------------------------------------------------------------------------------------------------------------------------------
--

create table reservation (id int primary key, name varchar(25), age int, sex char, add1 varchar(25),
add2 varchar(25), city varchar(25), state varchar(25), pin int, contactno bigint, trainid int, s_from
varchar(25), s_to varchar(25), tim time,dat date, cno int, seatno int,rid int)

create table train (id int primary key, name varchar(25), compartment int, seats int)

create table station (rid int foreign key(rid) references route, s_no int, s_name varchar(25))

create table route (id int foreign key(id) references train, rid int primary key, p_from varchar(25),
p_to varchar(25))

create table time (rid int foreign key(rid) references route, t_id int, s_no int, s_time time)

-------------------------------------------------------------------------------------------------------------------------------
--

insert into train values(1,'train 1',11,25)

insert into train values(2,'train 2',11,25)

insert into train values(3,'train 3',11,25)

insert into route values(1,1,'Tiruvanandapuram','Kanyakumari')

insert into route values(1,2,'Kanyakumari','Tiruvanandapuram')

insert into route values(2,3,'Karungal','Nagarcovil')

55
insert into route values(2,4,'Nagarcovil','Karungal')

insert into station values(1,1,'Tiruvanandapuram')

insert into station values(1,2,'Marthandam')

insert into station values(1,3,'Nagarcoil')

insert into station values(1,4,'Kanyakumari')

insert into station values(2,1,'Kanyakumari')

insert into station values(2,2,'Nagarcoil')

insert into station values(2,3,'Marthandam')

insert into station values(2,4,'Tiruvanandapuram')

insert into time values(1,1,1,'06:30')

insert into time values(1,1,2,'07:30')

insert into time values(1,1,3,'08:30')

insert into time values(1,1,4,'09:30')

insert into time values(2,1,1,'11:30')

insert into time values(2,1,2,'12:30')

insert into time values(2,1,3,'13:30')

insert into time values(2,1,4,'14:30')

-------------------------------------------------------------------------------------------------------------------------------
--

create procedure insertion (@id int, @name varchar(25), @age int, @sex char, @add1 varchar(25),
@add2 varchar(25), @city varchar(25), @state varchar(25), @pin int, @contactno bigint, @trainid
int, @s_from varchar(25), @s_to varchar(25), @tim time, @dat date, @cno int, @seatno int,@nu int)

as

insert into reservation values(@id, @name, @age, @sex, @add1, @add2, @city, @state, @pin,
@contactno, @trainid, @s_from, @s_to, @tim, @dat, @cno, @seatno,@nu)

56
create procedure selection (@id int)
as
select * from reservation where id = @id

create procedure getid


as
select id from reservation

create procedure trains


as
select id from train
create procedure gettraindetails(@id int)
as
select * from train where id = @id

create procedure get_from_station(@rid int)


as
select s_name from station where rid = @rid

create procedure gettime(@rid int, @s_name varchar(25))


as
begin
declare @s_no int
set @s_no = (select s_no from station where rid = @rid and s_name = @s_name)
select s_time from time where s_no = @s_no and rid = @rid
end

create procedure updation(@id int)


as
update reservation set seatno = 0 where id=@id

create procedure selectall


as
select * from reservation

Form 1

57
create procedure getrid(@id int)
as
select rid from route where id = @id

create procedure get_to_station(@rid int, @s_name varchar(25))


as
begin
declare @s_no int
set @s_no = (select s_no from station where rid=@rid and s_name=@s_name)
select s_name from station where rid=@rid and s_no > @s_no
end

create procedure get_id


as
select id from reservation where seatno <> 0

create view vw_details


as
select r.trainid, r.tim, r.dat, r.cno, r.seatno, r.rid, s.s_no, t.t_id from reservation r join station s on r.s_to
= s.s_name and r.rid = s.rid join time t on t.rid = r.rid and r.tim = t.s_time

create procedure getseat(@id int, @rid int, @s_name varchar(25), @time time, @dat date, @cno int)
as
begin
declare @s_no int, @t_id int
set @s_no = (select s_no from station where rid = @rid and s_name = @s_name)
set @t_id = (select t_id from time where rid = @rid and s_time = @time)
select seatno from vw_details where dat=@dat and cno=@cno and trainid=@id and rid = @rid and
t_id = @t_id and s_no >= @s_no
end
-------------------------------------------------------------------------------------------------------------------------------
--

Frontend Part

Form 1

Public Class Form1

58
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles
Button1.Click
Form2.Show()
End Sub

Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles


Button2.Click
Form3.Show()
End Sub

Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles


Button3.Click

Form 2

Form4.Show()
End Sub
End Clas

Form 2
Imports System.Data.SqlClient
Public Class Form2
Dim conn As SqlConnection
Dim mycomm As SqlCommand
Dim myreader As SqlDataReader
Dim s As Char

59
Dim id As Integer = 0
Dim s_no As Integer

Private Sub Form2_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles


MyBase.Load
conn = New SqlConnection()
conn.ConnectionString = "Data Source=Samar-PC\SQLEXPRESS;Integrated
Security=True;database=railway"
conn.Open()
mycomm = New SqlCommand()
mycomm.Connection = conn
mycomm.CommandText = "exec getid"
myreader = mycomm.ExecuteReader()
Do While myreader.Read()
id = myreader.GetValue(0)
Loop
myreader.Close()
id += 1
TextBox1.Text = id
mycomm.CommandText = "exec trains"
myreader = mycomm.ExecuteReader()
Do While myreader.Read()
ComboBox1.Items.Add(myreader.GetValue(0))
Loop
myreader.Close()
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles
Button1.Click
If RadioButton2.Checked Then
s = "F"
Else
s = "M"
End If
mycomm.CommandText = "exec insertion'" & TextBox1.Text & "','" & TextBox2.Text & " ','" &
TextBox3.Text & "','" & s & "','" & TextBox4.Text & "','" & TextBox5.Text & "','" & TextBox6.Text &
"','" & TextBox7.Text & "','" & TextBox8.Text & "','" & TextBox9.Text & "','" & ComboBox1.Text &
"','" & ComboBox3.Text & "','" & ComboBox4.Text & "','" & ComboBox5.Text & "','" &
DateTimePicker1.Text & "','" & ComboBox6.Text & "','" & ComboBox7.Text & "','" &
ComboBox2.Text & "'"
If mycomm.ExecuteNonQuery() Then
MsgBox("Reserved Successfully", , "Reservation")
id += 1
End If
End Sub

60
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles
Button2.Click
TextBox1.Text = id
TextBox2.Clear()
TextBox3.Clear()
TextBox4.Clear()
TextBox5.Clear()
TextBox6.Clear()
TextBox7.Clear()
TextBox8.Clear()
TextBox9.Clear()
TextBox10.Clear()
ClearCombobox()
End Sub

Private Sub ComboBox1_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As


System.EventArgs) Handles ComboBox1.SelectedIndexChanged
ClearCombobox()
mycomm.CommandText = "exec gettraindetails'" & ComboBox1.Text & "'"
myreader = mycomm.ExecuteReader()
myreader.Read()
TextBox10.Text = myreader.GetValue(1)
Dim i As Integer = 1
Do While i <= myreader.GetValue(2)
ComboBox6.Items.Add(i)
i += 1
Loop
s_no = myreader.GetValue(3)
myreader.Close()
ComboBox2.Items.Clear()
mycomm.CommandText = "exec getrid'" & ComboBox1.Text & "'"
myreader = mycomm.ExecuteReader()
Do While myreader.Read()
ComboBox2.Items.Add(myreader.GetValue(0))
Loop
myreader.Close()
End Sub

Private Sub ComboBox2_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As


System.EventArgs) Handles ComboBox3.SelectedIndexChanged
ComboBox4.Items.Clear()
mycomm.CommandText = "exec get_to_station'" & ComboBox2.Text & "','" & ComboBox3.Text
& "'"

61
myreader = mycomm.ExecuteReader()
Do While myreader.Read()
ComboBox4.Items.Add(myreader.GetValue(0))
Loop
myreader.Close()
ComboBox5.Items.Clear()
mycomm.CommandText = "exec gettime'" & ComboBox2.Text & "','" & ComboBox3.Text &"'"

myreader = mycomm.ExecuteReader()
Do While myreader.Read()
ComboBox5.Items.Add(myreader.GetValue(0))
Loop
myreader.Close()
End Sub

Private Sub ComboBox5_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As


System.EventArgs) Handles ComboBox6.SelectedIndexChanged
ComboBox7.Items.Clear()
Dim i As Integer = 1
Do While i <= s_no
ComboBox7.Items.Add(i)
i += 1
Loop
mycomm.CommandText = "exec getseat'" & ComboBox1.Text & "','" & ComboBox2.Text & "','"
& ComboBox3.Text & "','" & ComboBox5.Text & "','" & DateTimePicker1.Text & "','" &
ComboBox6.Text & "'"
myreader = mycomm.ExecuteReader()
Do While myreader.Read()
ComboBox7.Items.Remove(myreader.GetValue(0))
Loop
myreader.Close()
End Sub

Private Sub ClearCombobox()


ComboBox3.Text = ""
ComboBox4.Text = ""
ComboBox5.Text = ""
ComboBox6.Text = ""
ComboBox7.Text = ""
ComboBox3.Items.Clear()
ComboBox4.Items.Clear()
ComboBox5.Items.Clear()
ComboBox6.Items.Clear()
ComboBox7.Items.Clear()

62
End Sub

Private Sub ComboBox7_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As


System.EventArgs) Handles ComboBox2.SelectedIndexChanged
ComboBox3.Items.Clear()
mycomm.CommandText = "exec get_from_station'" & ComboBox2.Text & "'"
myreader = mycomm.ExecuteReader()
Do While myreader.Read()
ComboBox3.Items.Add(myreader.GetValue(0))

Form 3

Loop
myreader.Close()
End Sub
End Class
Form 3
Imports System.Data.SqlClient
Public Class Form3
Dim conn As SqlConnection
Dim mycomm As SqlCommand
Dim myreader As SqlDataReader

Private Sub Form3_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles


MyBase.Load
conn = New SqlConnection()
conn.ConnectionString = "Data Source=Samar-PC\SQLEXPRESS;Integrated
Security=True;database=railway"
conn.Open()
mycomm = New SqlCommand()

63
mycomm.Connection = conn
mycomm.CommandText = "exec get_id"
myreader = mycomm.ExecuteReader()
Do While myreader.Read()
ComboBox1.Items.Add(myreader.GetValue(0))
Loop
myreader.Close()
End Sub

Private Sub ComboBox1_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As


System.EventArgs) Handles ComboBox1.SelectedIndexChanged
mycomm.Connection = conn
mycomm.CommandText = "exec selection'" & ComboBox1.Text & "'"
myreader = mycomm.ExecuteReader()
myreader.Read()
TextBox1.Text = myreader.GetValue(1)
TextBox2.Text = myreader.GetValue(10)
TextBox3.Text = myreader.GetValue(11)
TextBox4.Text = myreader.GetValue(12)
TextBox5.Text = myreader.GetValue(14)
TextBox6.Text = myreader.GetValue(16)
TextBox7.Text = myreader.GetValue(15)
myreader.Close()
End Sub

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles


Button1.Click
mycomm.Connection = conn
mycomm.CommandText = "exec updation'" & ComboBox1.Text & "'"
If mycomm.ExecuteNonQuery() Then
MsgBox("Reservation Cancelled Successfully", , "Reservation")
End If

Form 4

End Sub

End Class

Form 4

64
Imports System.Data.SqlClient
Public Class Form4
Dim conn As SqlConnection
Dim mycomm As SqlCommand
Dim myreader As SqlDataReader
Private Sub Form4_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles
MyBase.Load
conn = New SqlConnection()
conn.ConnectionString = "Data Source=Samar-PC\SQLEXPRESS;Integrated
Security=True;database=railway"
conn.Open()
mycomm = New SqlCommand()
mycomm.Connection = conn
Dim c As Integer
With ListView1
.Clear()
.View = View.Details
.FullRowSelect = True
.GridLines = True
.FullRowSelect = True
.HoverSelection = True
.Scrollable = True
.Columns.Add("Id", 50, HorizontalAlignment.Left)
.Columns.Add("Name", 100, HorizontalAlignment.Left)
.Columns.Add("Age", 50, HorizontalAlignment.Left)
.Columns.Add("Sex", 50, HorizontalAlignment.Left)
.Columns.Add("Address Line 1", 100, HorizontalAlignment.Left)
.Columns.Add("Address Line 2", 100, HorizontalAlignment.Left)
.Columns.Add("City", 100, HorizontalAlignment.Left)
.Columns.Add("State", 100, HorizontalAlignment.Left)
.Columns.Add("Pin", 50, HorizontalAlignment.Left)
.Columns.Add("Contact no", 100, HorizontalAlignment.Left)
.Columns.Add("Train Id", 100, HorizontalAlignment.Left)
.Columns.Add("From", 100, HorizontalAlignment.Left)
.Columns.Add("To", 100, HorizontalAlignment.Left)
.Columns.Add("Date", 100, HorizontalAlignment.Left)
.Columns.Add("Cmp No", 100, HorizontalAlignment.Left)
.Columns.Add("Seat No", 100, HorizontalAlignment.Left)
.Columns.Add("Status", 100, HorizontalAlignment.Left)
End With
mycomm.CommandText = "exec selectall"
myreader = mycomm.ExecuteReader()
Do While myreader.Read()
ListView1.Items.Add(myreader.GetValue(0), 0)

65
ListView1.Items(c).SubItems.Add(myreader.GetValue(1))
ListView1.Items(c).SubItems.Add(myreader.GetValue(2))
ListView1.Items(c).SubItems.Add(myreader.GetValue(3))
ListView1.Items(c).SubItems.Add(myreader.GetValue(4))
ListView1.Items(c).SubItems.Add(myreader.GetValue(5))
ListView1.Items(c).SubItems.Add(myreader.GetValue(6))
ListView1.Items(c).SubItems.Add(myreader.GetValue(7))
ListView1.Items(c).SubItems.Add(myreader.GetValue(8))
ListView1.Items(c).SubItems.Add(myreader.GetValue(9))
ListView1.Items(c).SubItems.Add(myreader.GetValue(10))
ListView1.Items(c).SubItems.Add(myreader.GetValue(11))
ListView1.Items(c).SubItems.Add(myreader.GetValue(12))
ListView1.Items(c).SubItems.Add(myreader.GetValue(14))
ListView1.Items(c).SubItems.Add(myreader.GetValue(15))
ListView1.Items(c).SubItems.Add(myreader.GetValue(16))
If myreader.GetValue(16) <> 0 Then
ListView1.Items(c).SubItems.Add("Reserved")
Else
ListView1.Items(c).SubItems.Add("Cancelled")
End If
c += 1
Loop
myreader.Close()
End Sub
End Class

Result

Thus the VB.NET windows form application for Railway Reservation Management is created.

Ex.No.14 COP FRIENDLY APP-Eseva

Date:

Aim

66
To create a VB.NET windows form application for Cop Friendly App-Eseva.

Back End Part

Sql.sql

DROP DATABASE FirApp

CREATE DATABASE FirApp;

USE FirApp;

CREATE TABLE Police (


id INT IDENTITY(1,1) PRIMARY KEY,
name VARCHAR(50) NOT NULL,
no VARCHAR(20) NOT NULL,
password VARCHAR(50) NOT NULL
);

INSERT INTO Police (name, no, password)


VALUES
('John Smith', '101', 'password'),
('Alice Johnson', '102', 'password'),
('Bob Brown', '103', 'password');

CREATE TABLE Person (


id INT IDENTITY(1,1) PRIMARY KEY,
name VARCHAR(50) NOT NULL,
age INT NOT NULL,
address VARCHAR(100) NOT NULL,
aadhar VARCHAR(12) NOT NULL,
mobile VARCHAR(10) NOT NULL,
gender VARCHAR(10) NOT NULL CHECK (gender IN ('Male', 'Female'))
);

CREATE TABLE FIR (


id INT IDENTITY(1,1) PRIMARY KEY,
complainant_id INT NOT NULL,
police_id INT NOT NULL,
date DATETIME NOT NULL DEFAULT GETDATE(),
description VARCHAR(500) NOT NULL,
no VARCHAR(50) NOT NULL UNIQUE,
action_taken VARCHAR(500) NULL DEFAULT NULL,
status VARCHAR(20) NOT NULL CHECK (status IN ('Pending', 'Investigating', 'Closed')) DEFAULT
'Pending',
status_changed_by INT NOT NULL,
CONSTRAINT fk_complainant FOREIGN KEY (complainant_id) REFERENCES Person(id),
CONSTRAINT fk_police FOREIGN KEY (police_id) REFERENCES Police(id),
CONSTRAINT fk_status_changed_by FOREIGN KEY (police_id) REFERENCES Police(id)

67
);

CREATE TABLE CaseLog (


id INT IDENTITY(1,1) PRIMARY KEY,
fir_id INT NOT NULL,
police_id INT NOT NULL,
date DATETIME NOT NULL DEFAULT GETDATE(),
status VARCHAR(20) NOT NULL CHECK (status IN ('Pending', 'Investigating', 'Closed'))
);

GO

--- Functions
CREATE FUNCTION GetNextFIRNo()
RETURNS VARCHAR(10)
AS
BEGIN
DECLARE @nextFIRNo VARCHAR(10)

SELECT @nextFIRNo = 'FIR_' + RIGHT('0000' + CAST(ISNULL(MAX(SUBSTRING(no, 5, 4)), 0)


+ 1 AS VARCHAR(4)), 4)
FROM FIR

RETURN @nextFIRNo
END

GO

--- Procedures
CREATE PROCEDURE InsertPerson
@name VARCHAR(50),
@age INT,
@address VARCHAR(100),
@aadhar VARCHAR(20),
@mobile VARCHAR(15),
@gender VARCHAR(10),
@id INT OUTPUT
AS
BEGIN
SET NOCOUNT ON;

IF @name IS NULL OR @name = ''


BEGIN
RAISERROR('Name cannot be empty', 16, 1)
RETURN
END

IF @age < 0 OR @age > 150


BEGIN
RAISERROR('Age must be between 0 and 150', 16, 1)
RETURN

68
END

IF @aadhar IS NOT NULL AND EXISTS (SELECT 1 FROM Person WHERE aadhar = @aadhar)
BEGIN
RAISERROR('Aadhar number already exists', 16, 1)
RETURN
END

INSERT INTO Person (name, age, address, aadhar, mobile, gender)


VALUES (@name, @age, @address, @aadhar, @mobile, @gender)

SET @id = SCOPE_IDENTITY()

SELECT 'Person inserted successfully' AS Result, @id AS Id


END

GO

CREATE PROCEDURE InsertFIR


@person_id INT,
@description VARCHAR(500) = NULL,
@police_id INT,
@id INT OUTPUT
AS
BEGIN
SET NOCOUNT ON;

DECLARE @nextFIRNo VARCHAR(10)


SELECT @nextFIRNo = dbo.GetNextFIRNo()

IF (@person_id IS NULL)
BEGIN
RAISERROR('Complaint person ID cannot be NULL.', 16, 1);
RETURN;
END

IF (@description IS NULL)
BEGIN
RAISERROR('Description cannot be NULL.', 16, 1);
RETURN;
END

IF (@police_id IS NULL)
BEGIN
RAISERROR('Police ID cannot be NULL.', 16, 1);
RETURN;
END

INSERT INTO FIR (no, complainant_id, description, police_id, status_changed_by)


VALUES (@nextFIRNo, @person_id, @description, @police_id, @police_id);

69
SET @id = SCOPE_IDENTITY()

SELECT 'Fir inserted successfully' AS Result, @id AS Id


END

GO

CREATE PROCEDURE UpdateFIR


@id INT,
@action_taken VARCHAR(500),
@status_changed_by INT,
@status VARCHAR(20)
AS
BEGIN
SET NOCOUNT ON;

IF @id IS NULL
BEGIN
RAISERROR('FIR ID cannot be NULL.', 16, 1);
RETURN;
END

IF NOT EXISTS (SELECT 1 FROM FIR WHERE id = @id)


BEGIN
RAISERROR('FIR with given ID does not exist.', 16, 1);
RETURN;
END

UPDATE FIR
SET action_taken = @action_taken,
status_changed_by = @status_changed_by,
status = @status
WHERE id = @id;

SELECT 'FIR updated successfully.' AS Result;


END

GO

--- Triggers
CREATE TRIGGER trg_FIR_StatusChange
ON FIR
AFTER INSERT, UPDATE
AS
BEGIN
SET NOCOUNT ON;

IF UPDATE(status)
BEGIN
INSERT INTO CaseLog (fir_id, police_id, date, status)
SELECT inserted.id, inserted.police_id, GETDATE(), inserted.status

70
FROM inserted
END
END

GO

--- Views
CREATE VIEW CaseLogView
AS
SELECT cl.id AS CaseLogID, cl.date AS Date, f.id as FIRId, f.no AS FIRNo, p.name AS
PoliceOfficerName, cl.status AS Status
FROM CaseLog cl
INNER JOIN FIR f ON cl.fir_id = f.id
INNER JOIN Police p ON cl.police_id = p.id

GO

CREATE VIEW FIRList AS


SELECT f.id, f.no, p.name AS complaint_person_name, f.description, f.status, f.action_taken,
f.status_changed_by, po.name as police_name, po.no as police_no, po.id as police_id
FROM FIR f
INNER JOIN Person p ON f.complainant_id = p.id
INNER JOIN Police po ON f.police_id = po.id

GO

CREATE VIEW PersonListView AS


SELECT p.* FROM Person p

GO

Front End Part

LoginForm.vb

Public Class LoginForm


Public Shared PoliceId As Integer

Private Sub BtnLogin_Click(sender As Object, e As EventArgs) Handles BtnLogin.Click


Dim no As String = TbPoliceNo.Text
Dim password As String = TbPassword.Text

If SqlClient.Instance.PoliceLogin(no, password) Then


PoliceId = SqlClient.Instance.GetPoliceIdFromNo(no)

Me.Hide()
Dim nextForm As New FirList()
nextForm.ShowDialog()
Me.Close()
Else
' Failed login, show error message

71
MessageBox.Show("Invalid police number or password", "Login failed",
MessageBoxButtons.OK, MessageBoxIcon.Error)
End If
End Sub
End Class

FirList.vb

Public Class FirList


Private Sub FirList_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'TODO: This line of code loads data into the 'FirAppDataSet.FIRList' table. You can move, or
remove it, as needed.
Me.FIRListTableAdapter.Fill(Me.FirAppDataSet.FIRList)
Me.FIRListTableAdapter.Fill(Me.FirAppDataSet.FIRList)
End Sub

Private Sub BtnAddFIR_Click(sender As Object, e As EventArgs) Handles BtnAddFIR.Click


Dim frm As New FirForm(Nothing)
frm.ShowDialog()
Me.FIRListTableAdapter.Fill(Me.FirAppDataSet.FIRList)
End Sub

Private Sub DgvFirList_CellDoubleClick(sender As Object, e As DataGridViewCellEventArgs)


Handles DgvFirList.CellDoubleClick
If e.RowIndex >= 0 Then
Dim id As Integer =
Convert.ToInt32(DgvFirList.Rows(e.RowIndex).Cells("idDataGridViewTextBoxColumn").Value)

Dim frm As New FirForm(id)


frm.ShowDialog()

Me.FIRListTableAdapter.Fill(Me.FirAppDataSet.FIRList)
End If
End Sub

End Class

FirForm.vb

Public Class FirForm


Dim FirId As Integer? = Nothing

Public Sub New(Optional ByVal FirId As Integer? = Nothing)


InitializeComponent()

72
If Not FirId.HasValue Then
TbActionTaken.Enabled = False
CbStatus.Enabled = False
Me.FirId = Nothing
CbStatus.SelectedItem = "Pending"
LblCaseNo.Text = SqlClient.Instance.GetNextFIRNo()
Else
LoadFir(FirId)
End If
End Sub

Private Sub BtnAddNewPerson_Click(sender As Object, e As EventArgs) Handles


BtnAddNewPerson.Click
Dim frm = New AddPersonForm()
AddHandler frm.FormClosed, AddressOf AddPersonFormClosed
frm.ShowDialog()
End Sub

Private Sub AddPersonFormClosed(sender As Object, e As FormClosedEventArgs)


Me.PersonListViewTableAdapter.Fill(Me.FirAppDataSet.PersonListView)

If AddPersonForm.NewPersonId.HasValue Then
CbPersonName.SelectedValue = AddPersonForm.NewPersonId
End If
End Sub

Private Sub FirForm_Load(sender As Object, e As EventArgs) Handles MyBase.Load


Me.PersonListViewTableAdapter.Fill(Me.FirAppDataSet.PersonListView)
End Sub

Private Sub BtnSave_Click(sender As Object, e As EventArgs) Handles BtnSave.Click


Dim personId As Integer = CInt(CbPersonName.SelectedValue)
Dim description As String = TbCaseDetails.Text.Trim()

If String.IsNullOrEmpty(description) Then
MessageBox.Show("Please enter the case details.")
Return
End If

If Not FirId.HasValue Then


Dim policeId As Integer = LoginForm.PoliceId

Try
FirId = SqlClient.Instance.InsertFir(personId, description, policeId)
TbActionTaken.Enabled = True
CbStatus.Enabled = True
CbPersonName.Enabled = False
TbCaseDetails.Enabled = False

MessageBox.Show("FIR added successfully.")


Catch ex As Exception

73
MessageBox.Show("Error adding FIR. " & ex.Message)
End Try
Else
Dim actionTaken As String = TbActionTaken.Text.Trim()
Dim statusChangedBy As Integer = LoginForm.PoliceId
Dim status As String = CbStatus.Text.Trim()

Try
SqlClient.Instance.UpdateFir(FirId, actionTaken, statusChangedBy, status)

MessageBox.Show("FIR updated successfully.")


Catch ex As Exception
MessageBox.Show("Error updating FIR. " & ex.Message)
End Try
End If

CaseLogViewTableAdapter.FillBy(Me.FirAppDataSet.CaseLogView, Me.FirId)
End Sub

Private Sub LoadFir(firId As Integer)


TbActionTaken.Enabled = True
CbStatus.Enabled = True
BtnAddNewPerson.Visible = False
CbPersonName.Enabled = False
TbCaseDetails.Enabled = False

Me.FirId = firId

Dim fir = SqlClient.Instance.getFirById(firId)

Dim index = CbPersonName.FindStringExact(fir.Field(Of Integer)("complainant_id"))


If index >= 0 Then
CbPersonName.SelectedIndex = index
End If

TbActionTaken.Text = fir.Field(Of String)("action_taken")


TbCaseDetails.Text = fir.Field(Of String)("description")
LblCaseNo.Text = fir.Field(Of String)("no")
CbStatus.Text = fir.Field(Of String)("status")

CaseLogViewTableAdapter.FillBy(Me.FirAppDataSet.CaseLogView, firId)
End Sub

End Class

AddPersonForm.vb

Public Class AddPersonForm


Public Shared NewPersonId As Integer? = Nothing

74
Private Sub BtnAddPerson_Click(sender As Object, e As EventArgs) Handles BtnAddPerson.Click
Dim name As String = TbName.Text.Trim()
Dim age As Integer = Integer.Parse(TbAge.Text.Trim())
Dim address As String = TbAddress.Text.Trim()
Dim aadhar As String = If(String.IsNullOrEmpty(TbAadhar.Text.Trim()), Nothing,
TbAadhar.Text.Trim())
Dim mobile As String = TbMobileNo.Text.Trim()
Dim gender As String = CbGender.Text.Trim()

Dim id As Integer

Try
SqlClient.Instance.InsertPerson(name, age, address, aadhar, mobile, gender, id)
NewPersonId = id
Me.Close()
Catch ex As Exception
MessageBox.Show("An error occurred: " & ex.Message)
End Try
End Sub

Private Sub AddPersonForm_Load(sender As Object, e As EventArgs) Handles MyBase.Load


NewPersonId = Nothing
End Sub
End Class

ER DIAGRAM:

Screenshots:

75
76
77
Result

Thus the VB.NET windows form application for cop friendly app- Eseva is created.

78

You might also like