0% found this document useful (0 votes)
6 views57 pages

Print Dbmslab2023 V

The document outlines the practical work record for a student in the Database Management Systems Laboratory during the academic year 2022-2023. It includes a list of experiments covering SQL commands, database creation, data manipulation, and transaction control. Additionally, it provides examples of SQL commands for creating tables, inserting data, and managing database structures.

Uploaded by

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

Print Dbmslab2023 V

The document outlines the practical work record for a student in the Database Management Systems Laboratory during the academic year 2022-2023. It includes a list of experiments covering SQL commands, database creation, data manipulation, and transaction control. Additionally, it provides examples of SQL commands for creating tables, inserting data, and managing database structures.

Uploaded by

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

NAME :

YEAR :
BRANCH :
REGISTER NUMBER :

Certified to be the bonafide record of work done by the above student in IV th


SEMESTER in CS3481-DATABASE MANAGEMENT SYSTEMS
LABORATORY during the year 2022–2023.

Signature of the staff in-charge Signature of the Head of the Department

Submitted for the practical examination held on .

Internal Examiner External Examiner


INDEX
PAGE
SL.NO DATE TITLE MARK SIGNATURE
NO
CS3481 Database Management Systems Laboratory

LIST OF EXPERIMENTS:
1. Create a database table, add constraints (primary key, unique, check, Not null), insert
rows,update and delete rows using SQL DDL and DML commands.
2. Create a set of tables, add foreign key constraints and incorporate referential integrity.
3. Query the database tables using different ‘where’ clause conditions and also implement
aggregatefunctions.
4. Query the database tables and explore sub queries and simple join operations.
5. Query the database tables and explore natural, equi and outer joins.
6. Write user defined functions and stored procedures in SQL.
7. Execute complex transactions and realize DCL and TCL commands.
8. Write SQL Triggers for insert, delete, and update operations in a database table.
9. Create View and index for database tables with a large number of records.
10. Create an XML database and validate it using XML schema.
11. Create Document, column and graph based data using NOSQL database tools.
12. Develop a simple GUI based database application and incorporate all the above-mentioned
features
13. Case Study using any of the real life database applications from the following list
a) Inventory Management for a EMart Grocery Shop
b) Society Financial Management
c) Cop Friendly App – Eseva
d) Property Management – eMall
e) Star Small and Medium Banking and Finance
EX.NO 1: DDL,DML,DCL,TCL COMMANDS

DATA DEFINITION LANGUAGE(DDL)


(CREATE,DESC,ALTER,TRUNCATE,DROP,RENAME)

//1.CREATE COMMAND

//TABLE CREATION:
SQL>create table exp1_accounts(Accountno number(5),Customername varchar2(10),Balance
number(5),Accountstatus varchar2(10),Branchname varchar(15));
Table created.

//TABLE DESCRIPTION:
SQL> desc exp1_accounts;
Name Null? Type
---------------------- -------- -------------------
ACCOUNTNO NUMBER(5)
CUSTOMERNAME VARCHAR2(10)
BALANCE NUMBER(5)
ACCOUNTSTATUS VARCHAR2(10)
BRANCHNAME VARCHAR2(15)

//select all records from table(initially empty rows-no records)


SQL> select *from exp1_accounts;
no rows selected

//INSERT RECORDS:
SQL> insert into exp1_accounts values(101,'smith',500,'closed','chennai');
1 row created.
SOL>insert into exp1_accounts values(102,'williams',600,'active','trichy');
1row created.
SQL> insert into exp1_accounts values(103,'jones',700,'closed','madurai');
1 row created.
SQL> insert into exp1_accounts values(104,'henry',800,'inactive','chennai');
1 row created.
SQL>insert into exp1_accounts values(105,'turner',900,'closed','kerela');
1 row created
//selects or view all records from table:
SQL> select *from exp1_accounts;
ACCOUNTNO CUSTOMERNAME BALANCE ACCOUNTSTATUS BRANCHNAME
---------- ---------- ---------- ---------- ---------------
101 smith 500 closed chennai
102 williams 600 active trichy
103 jones 700 closed madurai
104 henry 800 inactive chennai
105 turner 900 closed kerela

2)ALTER COMMAND:
a) Add New Column to the existing table using alter command
SQL> alter table exp1_accounts add password varchar2(10);
Table altered.

//DESCRIPTION OF A TABLE:
SQL> desc exp1_accounts;
Name Null? Type
---------------------- -------- -------------------
ACCOUNTNO NUMBER(5)
CUSTOMERNAME VARCHAR2(10)
BALANCE NUMBER(5)
ACCOUNTSTATUS VARCHAR2(10)
BRANCHNAME VARCHAR2(15)
PASSWORD VARCHAR2(10)

SQL> select *from exp1_accounts;


ACCOUNTNO CUSTOMERNA BALANCE ACCOUNTSTA BRANCHNAME
PASSWORD
---------- ---------- ---------- ---------- --------------- ----------

101 smith 500 closed chennai


102 williams 600 active trichy
103 jones 700 closed madurai
104 henry 800 inactive chennai
105 turner 900 closed kerela
//INSERT A NEW RECORD AFTER ALTER TABLE STRUCTURE
(Here New column added i.e PASSWORD)//pass values to new column
i.e password
SQL> insert into exp1_accounts values(106,'prem',800,'closed','trichy','2ss');
1 row created.
SQL> insert into exp1_accounts values(107,'shai',900,'open','chennai','1bb');
1 row created.
SQL> select *from exp1_accounts;
ACCOUNTNO CUSTOMERNA BALANCE ACCOUNTSTA BRANCHNAME
PASSWORD
---------- ---------- ---------- ---------- --------------- ----------

101 smith 500 closed chennai


102 williams 600 active trichy
103 jones 700 closed madurai
104 henry 800 inactive chennai
105 turner 900 closed kerela
106 prem 800 closed trichy 2ss
107 shai 900 open chennai 1bb
7 rows selected.

//DROP COLUMN FROM TABLE USING ALTER COMMAND


SQL> alter table exp1_accounts drop column password; Table altered.

//After Column Drop Table


SQL> select *from exp1_accounts;
ACCOUNTNO CUSTOMERNA BALANCE ACCOUNTSTA
BRANCHNAME
---------- ---------- ---------- ---------- ---------------
101 smith 500 closed chennai
102 williams 600 active trichy
103 jones 700 closed madurai
104 henry 800 inactive chennai
105 turner 900 closed kerela
106 prem 800 closed trichy
107 shai 900 open chennai
7 rows selected.

//RENAME COLUMN NAME IN TABLE


SQL> alter table exp1_accounts rename column branchname to branchlocation;
Table altered.
//View the table Structure
SQL> desc exp1_accounts;
Name Null? Type
--------------------------------- -------- ---------------
ACCOUNTNO NUMBER(5)
CUSTOMERNAME VARCHAR2(10)
BALANCE NUMBER(5)
ACCOUNTSTATUS VARCHAR2(10)
BRANCHLOCATION VARCHAR2(15)

//CHANGE COLUMN-DATATYPE SIZE


//existing table size: customername column size 10

SQL> desc exp1_accounts;


Name Null? Type
----------------------------------------------------- -------- ------------------------------------
ACCOUNTNO NUMBER(38)
CUSTOMERNAME VARCHAR2(10)
BALANCE NUMBER(5)
ACCOUNTSTATUS VARCHAR2(10)
BRANCHLOCATION VARCHAR2(15)

//change the size of column datatype


//customername varchar size now 20
SQL> alter table exp1_accounts modify customername varchar2(20);
Table altered.

SQL> desc exp1_accounts;


Name Null? Type
----------------------------------------------------- -------- ------------------------------------
ACCOUNTNO NUMBER(5)
CUSTOMERNAME VARCHAR2(20)
BALANCE NUMBER(5)
ACCOUNTSTATUS VARCHAR2(10)
BRANCHLOCATION VARCHAR2(15)
//Change column datatype in table
//from number to int.no error but default size only will get change
//initial number 5 to 38 for int.
//number is good choice for numerical data

SQL> alter table exp1_accounts modify accountno int;


Table altered.

SQL> desc exp1_accounts;


Name Null? Type
------------------ -------- ----------------
ACCOUNTNO NUMBER(38)
CUSTOMERNAME VARCHAR2(10)
BALANCE NUMBER(5)
ACCOUNTSTATUS VARCHAR2(10)
BRANCHLOCATION VARCHAR2(15)

//change column datatype from varchar to number.


//error will come.bz table have already tuples/rows
//solution truncate and change column datatype as per user choice

SQL> alter table exp1_accounts modify accountno varchar2(10);


ERROR at line 1:
ORA-01439: column to be modified must be empty to change datatype

SQL> truncate table exp1_accounts;


Table truncated.

//change accountno column datatype from number to varchar


SQL> alter table exp1_accounts modify accountno varchar2(10);
Table altered.

//view column datatype after change


SQL> desc exp1_accounts;
Name Null? Type
----------------------------------------------------- -------- ------------------------------------
ACCOUNTNO VARCHAR2(10)
CUSTOMERNAME VARCHAR2(20)
BALANCE NUMBER(5)
ACCOUNTSTATUS VARCHAR2(10)
BRANCHLOCATION VARCHAR2(15)

//again change accountno column datatype from varchar to number


SQL> alter table exp1_accounts modify accountno number;
Table altered.
//view column datatype after change
SQL> desc exp1_accounts;
Name Null? Type
-------------------------- -------- ------------------------------------
ACCOUNTNO NUMBER
CUSTOMERNAME VARCHAR2(20)
BALANCE NUMBER(5)
ACCOUNTSTATUS VARCHAR2(10)
BRANCHLOCATION VARCHAR2(15)

//TRUNACATE
SQL> truncate table exp1_accounts;
Table truncated.

SQL> select *from exp1_accounts;


no rows selected

SQL> desc IT_exp1_account;


Name Null? Type
-------------------- ----------- -----------
ACCOUNTNO NUMBER (5)
CUSTOMERNAME VARCHAR2 (10)
BALANCE NUMBER (5)
ACCOUNTSTATUS VARCHAR2 (7)
BRANCHNAME VARCHAR2 (15)
PASSWORD VARCHAR2(10)

//DROP command
SQL> drop table IT_exp1_account;
Table dropped.

SQL> desc IT_exp1_account;


ERROR:ORA-04043: object IT_exp1_account does not exist

//Rename a table
SQL> alter table exp1_accounts rename to temptable1;
Table altered.

//ADD Single COLUMN IN TABLE


ALTER TABLE customers ADD customer_name varchar2(45);

//ADD MULTIPLE COLUMNS IN TABLE


ALTER TABLE customers ADD (customer_name varchar2(45),city varchar2(40));
//MODIFY COLUMN DATATYPE IN TABLE
ALTER TABLE customers MODIFY customer_name varchar2(100) NOT NULL;

//DROP COLUMN IN TABLE


ALTER TABLE customers DROP COLUMN customer_name;

//RENAME COLUMN NAME IN TABLE


ALTER TABLE customers RENAME COLUMN customer_name TO cname;

//RENAME TABLE
ALTER TABLE customers RENAME TO contacts;

DATA MANIPULATION LANGUAGE(DML)


(INSERT,UPDATE,DELETE)

//CREATION OF TABLE
SQL>create table exp1_students(sid number(5),sname varchar2(20),sage number(10),sarea
varchar2(20),sdept varchar2(20));
Table created.

//insert command
//INSERTION OF VALUES INTO THE TABLE
SQL> insert into exp1_students values(101,'ashwin',19,'annanagar','eee');
1 row created.
SQL> insert into exp1_students values(102,'bhavesh',18,'nungambakkam','cse');
1 row created.
SQL> insert into exp1_students values(103,'pruthvik',20,'annanagar','ece');
1 row created.
SQL> insert into exp1_students values(104,'charith',20,'kilpauk','mech');
1 row created.

SQL> select * from exp1_students;


SNAME SID SAGE SAREA SDEPT
------------------------------ ---- -- ---------
Ashwin 101 19 annanagar eee
bhavesh 102 18 nungambakkam cse
pruthvik 103 20 annanagar ece
charith 104 20 kilpauk mech
//select specific columns only
SQL> select sid,sname from exp1_students;
SID SNAME
-------------
101 ashwin
102 bhavesh
103 pruthvik
104 charith

//UPDATE command
SQL>update exp1_students set sage=25 where sid=101;
1 row updated.
SQL>update exp1_students set sage=78 where sid=102;
1 row updated.

sql>select * from exp1_students;


SID SNAME SAGE SAREA SDEPT
---------- ---------------- --------------------
101 ashwin 25 annanagar eee
102 bhavesh 78 nungambakkam cse
103 pruthvik 20 annanagar ece
104 charith 20 kilpauk mech

//DELETE command with where condition


SQL> delete from exp1_students where sid=1;
1 row deleted//only one row delted

//DELETE command without where condition


SQL> delete from exp1_students;
4 rows deleted.//all rows deleted

DATA CONTROL LANGUAGES(DCL)


(COMMIT, ROLLBACK, SAVEPOINT)

//TABLE CREATION
//ROLLBACK COMMAND DEMO
SQL>create table exp1_persons(pid number(5),firstname varchar2(10),lastname
varchar2(10),address varchar2(10),age number(5));
Table created.

//Insert 4records using insert command.


SQL> insert into exp1_persons values(1,'prettina','anne','bangalore',14);
insert into exp1_persons values(2,'Benitto','Anish','trichy',24)
insert into exp1_persons values(3,'Raj','Anita','Chennai',24)
insert into exp1_persons values(4,'kumar','Ashok','Coimbatore',30)
SQL> select * from exp1_persons;
PID LASTNAME FIRSTNAME ADDRESS AGE
------- ---------- ---------- ------------ -------
1 Prettina Anne Bangalore 14
2 Benitto Anish Trichy 24
3 Raj Anita Chennai 27
4 Kumar Ashok Coimbatore 30
4 rows selected.

//SAVE POINT DEMO


SQL> savepoint s1;
Savepoint created.

SQL> delete from exp1_persons;


4 rows deleted.

SQL> select * from exp1_persons;


no rows selected

SQL> rollback to savepoint s1;


Rollback complete.

SQL> select * from person;


PID LASTNAME FIRSTNAME ADDRESS AGE
------- ---------- ---------- ------------ -------
1 Prettina Anne Bangalore 14
2 Benitto Anish Trichy 24
3 Raj Anita Chennai 27
4 Kumar Ashok Coimbatore 30

//commit example(commit makes the permanent changes in database)


//COMMIT COMMAND
SQL> delete from exp1_persons where pid=1;
1 row deleted.

SQL> rollback to savepoint s1;


Rollback complete.
SQL> select *from exp1_persons;
PID FIRSTNAME LASTNAME ADDRESS AGE
---------- ---------- ---------- ---------- ----------
1 prettina anne bangalore 14
2 Benitto Anish trichy 24
3 Raj Anita Chennai 24
4 kumar Ashok Coimbatore 30
SQL> commit;
Commit complete.

SQL> delete from exp1_persons where pid=1;


1 row deleted.

SQL> select *from exp1_persons;


PID FIRSTNAME LASTNAME ADDRESS AGE
---------- ---------- ---------- ---------- ----------
2 Benitto Anish trichy 24
3 Raj Anita Chennai 24
4 kumar Ashok Coimbatore 30

SQL> rollback to savepoint s1;


rollback to savepoint s1
*
ERROR at line 1:
ORA-01086: savepoint 'S1' never established in this session or is invalid

TRANSACTION CONTROL LANGUAGE(TCL)


(GRANT AND REVOKE)
GRANT command
//Grant Privileges on Table
You can grant users various privileges to tables.
These privileges can be any combination of
SELECT, INSERT, UPDATE, DELETE, REFERENCES, ALTER, INDEX, or ALL.

syntax: GRANT privileges ON object TO user;

Privilege Description
SELECT Ability to perform SELECT statements on the table.
INSERT Ability to perform INSERT statements on the table.
UPDATE Ability to perform UPDATE statements on the table.
DELETE Ability to perform DELETE statements on the table.
REFERENCES Ability to create a constraint that refers to the table.
ALTER Ability to perform ALTER TABLE statements to change the table
definition.
INDEX Ability to create an index on the table with the create index statement.
ALL All privileges on table.
Example:
SQL>GRANT SELECT,INSERT,UPDATE,DELETE ON suppliers TO smithj;
SQL>GRANT ALL ON suppliers TO smithj;
SQL>GRANT SELECT ON suppliers TO public;

Revoke command
//Revoke Privileges on Table Example:
REVOKE DELETE ON suppliers FROM anderson;
REVOKE ALL ON suppliers FROM anderson; REVOKE
ALL ON suppliers FROM public;

Suppliers is database name and Anderson is user name;

DATA QUERY LANGUAGE(DQL)


(select)
Data Query Language (DQL) is used to fetch the data from the database. It uses only one
command:

SELECT:
This command helps you to select the attribute based on the condition described by the
WHERE clause.
Syntax:
SELECT expressions FROM TABLES WHERE conditions;

For example:
SQL> SELECT FirstName FROM Student WHERE RollNo>15;
EXP.NO : 2 INTEGRITY CONSTRAINTS
1)primary key 2)foreign key 3)check 4)unique 5)not null

//Primary Key Constraints


SQL> create table exp2_employee(empid number(8) primary key,empname
varchar(10),empsalary number(6));
Table created.

SQL> desc exp2_employee;


Name Null? Type
----------------- --------------------
EMPID NOTNULL NUMBER(8)
EMPNAME VARCHAR2(10)
EMPSALARY NUMBER(6)

//insert tuples/records
SQL> insert into exp2_employee values(101,'tamil',15000);
1 row created.
SQL> insert into exp2_employee values(102,'hayes',14000);
1 row created.
SQL> insert into exp2_employee values(103,'william',12000);
1 row created.

SQL> insert into exp2_employee values(103,'jhon',14000);


insert into exp2_employee values(103,'jhon',14000)
*ERROR at line 1:
ORA-00001: unique constraint (SCOTT.SYS_C0011549) violated

//Foreign Key Constraints:


Table Creation:
SQL>create table exp2_empdept(deptid number(8),deptname varchar(8),deptlocation
varchar(8),foreign key(deptid)references exp2_employee);
Table created.

SQL> desc exp2_empdept;


Name Null? Type
------------------------ ----------------------------
DEPTID NUMBER(8)
DEPTNAME VARCHAR2(8)
DEPTLOCATION VARCHAR2(8)
//view exp2_employee table for reference
SQL> select *from exp2_employee;
EMPID EMPNAME EMPSALARY
---------- ---------- ----------
101 tamil 15000
102 hayes 14000
103 william 12000

//insert 1record into empdept table


SQL> insert into exp2_empdept values (102,'HR','trichy');
1 row created.

SQL> select *from exp2_empdept;


DEPTID DEPTNAME DEPTLOCA
---------- -------- --------
101 IT chennai
102 HR trichy

//insert new record which are not in employee table.


SQL> insert into exp2_empdept values (1,'IT','chennai');
insert into exp2_empdept values (1,'IT','chennai')
*ERROR at line 1:
ORA-02291: integrity constraint (SCOTT.SYS_C0011558) violated - parent key not
found

//NOT NULL, UNIQUE and CHECK Constraints:


//Table Creation:
SQL>create table exp2_accounts(accno number(10) NOT NULL, accounttype
varchar(10),check(accounttype in('SB','FD','RD')),branchid number(10) unique);
Table created.

SQL> desc exp2_accounts;


Name Null? Type
--------------------------------------
ACCNO NOT NULL NUMBER (10)
ACCOUNTTYPE VARCHAR2 (10)
BRANCHID NUMBER (10)

//Insert Records in Table:


SQL>insert into exp2_accounts values (1,'SB', 39)
1 row created.
SQL> insert into exp2_accounts values (2,'FD', 40);
SQL> insert into exp2_accounts values (3,'RD', 41);
1 row created.

//View Records from Table:


SQL> select *from exp2_accounts;
ACCNO ACCOUNTTYPE BRANCHID
-------- ---------- ----------
1 SB 39
2 FD 40
3 RD 41

//NOT NULL CONSTRAINT CHECKING:


SQL> insert into exp2_accounts values ('SB', 39)
*ERROR at line 1:ORA-00947: not enough values

//UNIQUE CONSTRAINT CHECKING:


SQL> insert into exp2_accounts values (4,'SB', 41);
Insert into exp2_accounts values (4,'SB', 41)
*ERROR at line 1:ORA-00001: unique constraint(SYSTEM.SYS_C003055) violated

//CHECK CONSTRAINT CHECKING:


SQL> insert into exp2_accounts values(3,'GL',39);
insert into exp2_accounts values(3,'GL',39)
*ERROR at line 1:ORA-02290: check constraint (SCOTT.SYS_C0011560) violated
EX.NO3 WHERE CLAUSE CONDITION AND AGGREGATE
FUNCTIONS

//Create table
SQL>create table exp3_student(sid number(5) primary key,sname varchar2(20),sdept
varchar2(20),mark number(4));
Table created.

SQL> desc exp3_student;


Name Null? Type
------------------ -------- ----------------------------
SID NOT NULL NUMBER(5)
SNAME VARCHAR2(20)
SDEPT VARCHAR2(20)
MARK NUMBER(4)

SQL> insert into exp3_student values(100,'hayes','cse',40);


1 row created.
SQL> insert into exp3_student values(102,'william','eee',50);
1 row created.
SQL> insert into exp3_student values(101,'jhon','ece',60);
1 row created.
SQL> insert into exp3_student values(103,'smith','ece',70);
1 row created.
SQL> insert into exp3_student values(105,'william','cse',80);
1 row created.

SQL> select *from exp3_student;


SID SNAME SDEPT MARK
---------- -------------------- -------------------- ----------
100 hayes cse 40
102 william eee 50
101 jhon ece 60
103 smith ece 70
105 william cse 80

//ARITHMETIC OPERATION
SQL> select sname,mark+10 from exp3_student;
SNAME MARK+10
-------------------- ----------
hayes 50
william 60
jhon 70
smith 80
william 90
//CONCATENATION OPERATOR
SQL> select sname || 'is a'||sdept||'engineer' as profession from exp3_student;

PROFESSION
---------------------------
hayes is a cse engineer
william is a eee engineer
jhon is a ece engineer
smith is a ece engineer
william is a cse engineer

//distinct operation
SQL> select distinct sdept from exp3_student;
SDEPT
-----------
cse
eee
ece

//list cse department students only


SQL> select *from exp3_student where sdept='cse';
SID SNAME SDEPT MARK
---------- -------------------- -------------------- ----------
100 hayes cse 40
105 william cse 80

//Between operator
SQL> select *from exp3_student where sid between 100 and 102;

SID SNAME SDEPT MARK


---------- -------------------- -------------------- ----------
100 hayes cse 40
102 william eee 50
101 jhon ece 60

//In predicate
SQL> select *from exp3_student where sid in(102,103);
SID SNAME SDEPT MARK
---------- -------------------- -------------------- ----------
102 william eee 50
103 smith ece 70
SQL> select *from exp3_student;
SID SNAME SDEPT MARK
---------- -------------------- -------------------- ----------
100 hayes cse 40
102 william eee 50
101 jhon ece 60
103 smith ece 70
105 william cse 80

//Pattern matching string


SQL> select *from exp3_student where sname like 's%';
SID SNAME SDEPT MARK
---------- -------------------- -------------------- ----------
103 smith ece 70

SQL> select *from exp3_student where sname like '%s';


SID SNAME SDEPT MARK
---------- -------------------- -------------------- ----------
100 hayes cse 40

SQL> select *from exp3_student where sname like '%s%';


SID SNAME SDEPT MARK
---------- -------------------- -------------------- ----------
100 hayes cse 40
103 smith ece 70

//AND operator
SQL> select *from exp3_student where sid>102 and sname='smith';
SID SNAME SDEPT MARK
---------- -------------------- -------------------- ----------
103 smith ece 70

//OR operator
SQL> select *from exp3_student where sid>102 or sname='smith';
SID SNAME SDEPT MARK
---------- -------------------- -------------------- ----------
103 smith ece 70
105 william cse 80

SQL> select *from exp3_student where sid>102 or sname='tamil';


SID SNAME SDEPT MARK
---------- -------------------- -------------------- ----------
103 smith ece 70
105 william cse 80
//select all records
SQL> select *from exp3_student;
SID SNAME SDEPT MARK
---------- -------------------- -------------------- ----------

100 hayes cse 40


102 william eee 50
101 jhon ece 60
103 smith ece 70
105 william cse 80

//not in predicate
SQL> select *from exp3_student where sid not in(102,103);
SID SNAME SDEPT MARK
---------- -------------------- -------------------- ----------

100 hayes cse 40


101 jhon ece 60
105 william cse 80

//update using where condition


SQL> update exp3_student set sdept='civil' where sid=101;
1 row updated.

//after update table records


SQL> select *from exp3_student;
SID SNAME SDEPT MARK
---------- -------------------- -------------------- ----------

100 hayes cse 40


102 william eee 50
101 jhon civil 60
103 smith ece 70
105 william cse 80

//delete operation (write your own query)

//AGGREGATE FUNCTIONS(min,max,count,sum,avg)
SQL> select *from exp3_student;
SID SNAME SDEPT MARK
---------- -------------------- -------------------- ----------

100 hayes cse 40


102 william eee 50
101 jhon civil 60
103 smith ece 70
105 william cse 80
//count function
SQL> select count(sid) as Result from exp3_student;
RESULT
----------
5
//minimum function
SQL> select min(mark) as Result from exp3_student;
RESULT
----------
40

//max function
SQL> select max(mark) as Result from exp3_student;
RESULT
----------
80
//average function
SQL> select avg(mark) as Result from exp3_student;
RESULT
----------
60
//count function
SQL> select count(*) as Result from exp3_student;
RESULT
----------
5

//HAVING CLAUSE EXAMPLE


//VIEW TABLE RECORDS
SQL> select *from exp3_student;
SID SNAME SDEPT MARK
---------- -------------------- -------------------- ----------

100 hayes cse 40


101 jhon ece 60
102 william eee 50
103 smith ece 70
105 william cse 80

//GROUPBY BY DEPARTMENT AND TOTAL MARKS

SQL> select count(*) as total,sdept as deptname from exp3_student group by sdept;


TOTAL DEPTNAME
---------- --------------------
2 cse
1 eee
2 ece
//find all total for all dept
SQL> select sdept,sum(mark) as total from exp3_student group by sdept;
SDEPT TOTAL
-------------------- ----------

cse 120
eee 50
ece 130

//having clause is used when we use groupby command


SQL> select sdept,sum(mark) as total from exp3_student group by sdept having
sum(mark)>50;
SDEPT TOTAL
-------------------- ----------
cse 120
ece 130

//groupby and mention condition with having clause


SQL> select sdept,sum(mark) as total from exp3_student group by sdept having
sum(mark)>50 and sdept='cse';

SDEPT TOTAL
-------------------- ----------
cse 120

//having clause
SQL> select sdept,sum(mark) as total from exp3_student group by sdept having
sum(mark)<=50;

SDEPT TOTAL
-------------------- ----------
eee 50
EX.NO4 : SUB QUERY AND SIMPLE JOIN OPERATIONS

Procedure to join queries


1)create table1 and insert 5records
2)create table2 and insert 5 records
3)create common column between table1 and table2
4)execute join conditions

//JOINS DEMO
//table1
SQL> create table exp4_student1(sid number(5),sname varchar2(20));
Table created.

//table1 structure
SQL> desc exp4_student1;
Name Null? Type
----------- -------- ----------------------------
SID NUMBER(5)
SNAME VARCHAR2(20)

//create table2
SQL> create table exp4_student2(sid number(5),sdept varchar2(10),marks number(5));
Table created.

//table2 structure
SQL> desc exp4_student2;
Name Null? Type
----------------------------------------- -------- ----------------------------
SID NUMBER(5)
SDEPT VARCHAR2(10)
MARKS NUMBER(5)

//insert records into table1


SQL> insert into exp4_student1 values(100,'tamil');
1 row created.
SQL> insert into exp4_student1 values(101,'jhon');
1 row created.
SQL> insert into exp4_student1 values(102,'hayes');
1 row created.
SQL> insert into exp4_student1 values(103,'william');
1 row created.
SQL> insert into exp4_student1 values(104,'smith');
1 row created.
SQL> select *from exp4_student1;
SID SNAME
---------- --------------------
100 tamil
101 jhon
102 hayes
103 william
104 smith

//table2 records
SQL> insert into exp4_student2 values(100,'cse',70);
1 row created.
SQL> insert into exp4_student2 values(101,'ece',80);
1 row created.
SQL> insert into exp4_student2 values(102,'eee',90);
1 row created.

SQL> select *from exp4_student2;


SID SDEPT MARKS
---------- ---------- ----------

100 cse 70
101 ece 80
102 eee 90

SQL> select *from exp4_student1;


SID SNAME
---------- --------------------
100 tamil
101 jhon
102 hayes
103 william
104 smith
JOINS

Inner Join(simple join)


SQL> select exp4_student1.sid,exp4_student1.sname,exp4_student2.sdept from
exp4_student1 inner join exp4_student2 on (exp4_student1.sid=exp4_student2.sid);
SID SNAME SDEPT
---------- -------------------- ----------
100 tamil cse
101 jhon ece
102 hayes eee

//without inner keyword=inner join


SQL> select exp4_student1.sid,exp4_student1.sname,exp4_student2.sdept from
exp4_student1 join exp4_student2 on (exp4_student1.sid=exp4_student2.sid);
SID SNAME SDEPT
---------- -------------------- ----------
100 tamil cse
101 jhon ece
102 hayes eee

EQUI JOIN(The join condition or the comparison operator present in the WHERE
clause of the select statement)

SQL>select exp4_student1.sid,exp4_student1.sname,exp4_student2.sdept from


exp4_student1,exp4_student2 where exp4_student1.sid=exp4_student2.sid;
SID SNAME SDEPT
---------- -------------------- ----------
100 tamil cse
101 jhon ece
102 hayes eee

//LEFT OUTER JOINS (also called as Left Joins)


SQL> select exp4_student1.sid,exp4_student1.sname,exp4_student2.sdept from
exp4_student1 left outer join exp4_student2 on (exp4_student1.sid=exp4_student2.sid);
SID SNAME SDEPT
---------- -------------------- ----------
100 tamil cse
101 jhon ece
102 hayes eee
103 william
104 smith
//RIGHT OUTER JOINS (also called as Right Joins)
SQL> select exp4_student1.sid,exp4_student1.sname,exp4_student2.sdept from
exp4_student1 right outer join exp4_student2 on (exp4_student1.sid=exp4_student2.sid);

SID SNAME SDEPT


---------- -------------------- ----------
100 tamil cse
101 jhon ece
102 hayes eee

//FULL OUTER JOINS (also called as Full Joins)


SQL> select exp4_student1.sid,exp4_student1.sname,exp4_student2.sdept from
exp4_student1 full outer join exp4_student2 on (exp4_student1.sid=exp4_student2.sid);

SID SNAME SDEPT


---------- -------------------- ----------
100 tamil cse
101 jhon ece
102 hayes eee
103 william
104 smith

//NESTED QUERIES/SUB QUERIES


//view all records from table2
SQL> select *from exp4_student2;
SID SDEPT MARKS
---------- ---------- ----------

100 cse 70
101 ece 80
102 eee 90
//first view all sid from second table
SQL> select sid from exp4_student2;
SID
----------
100
101
102

//select sid from table2 and pass to table1 to view student name
SQL> select sname from exp4_student1 where exp4_student1.sid in(select sid from
exp4_student2);
SNAME
--------------------
tamil
jhon
hayes

//in keyword predicate in nested query


//pass sid values to table using nested query and then filter record from table1 based on inner
query answer

SQL> select sname,sid from exp4_student1 where exp4_student1.sid in(select sid from
exp4_student2);
SNAME SID
-------------------- ----------

tamil 100
jhon 101
hayes 102

//not in predicate in nested query


SQL> select sname,sid from exp4_student1 where exp4_student1.sid not in(select sid from
exp4_student2);
SNAME SID
-------------------- ----------
william 103
smith 104

//some keyword
SQL> select sid,sdept,marks from exp4_student2 where marks >some (select marks from
exp4_student2 where sdept='cse');
SID SDEPT MARKS
---------- ---------- ----------
102 eee 90
101 ece 80
SQL> select sid,sdept,marks from exp4_student2 where marks >=some (select marks
from exp4_student2 where sdept='cse');
SID SDEPT MARKS
---------- ---------- ----------

102 eee 90
101 ece 80
100 cse 70

//any keyword(alternative keyword for some)(some and any keyword answer is


same) SQL> select sid,sdept,marks from exp4_student2 where marks >any (select
marks from exp4_student2 where sdept='cse');
SID SDEPT MARKS
---------- ---------- ----------
102 eee 90
101 ece 80

SQL> select sid,sdept,marks from exp4_student2 where marks >=any (select marks
from exp4_student2 where sdept='cse');
SID SDEPT MARKS
---------- ---------- ----------

102 eee 90
101 ece 80
100 cse 70

//all keyword

SQL> select sid,sdept,marks from exp4_student2 where marks >all (select marks
from exp4_student2 where sdept='cse');

SID SDEPT MARKS


---------- ---------- ----------
101 ece 80
102 eee 90

SQL> select sid,sdept,marks from exp4_student2 where marks <all (select marks
from exp4_student2 where sdept='cse');
no rows selected

SQL> select sid,sdept,marks from exp4_student2 where marks <=all (select marks
from exp4_student2 where sdept='cse');
SID SDEPT MARKS
---------- ---------- ----------
100 cse 70
EX.NO 5 TRIGGERS

//first login as database administrator


Enter user-name: conn /as sysdba
Enter password:(empty)just press enter no password

Connected to:
Personal Oracle Database 11g Release 11.2.0.1.0 - Production
With the Partitioning, OLAP, Data Mining and Real Application Testing options

//grant all rights to scott user


SQL> grant all privileges to scott identified by tiger;
Grant succeeded.
SQL> exit

//now login to scott user


//create table
SQL> create table tbl1(empid number(5),empname varchar2(20),empsalary number(6));
Table created.

SQL> desc tbl1;


Name Null? Type
----------- ----------------------------
EMPID NUMBER(5)
EMPNAME VARCHAR2(20)
EMPSALARY NUMBER(6)

//insert 3records
SQL> insert into tbl1 values(106,'hayes',12000);
1 row created.
SQL> insert into tbl1 values(107,'jhon',11000);
1 row created.
SQL> insert into tbl1 values(108,'smith',10000);
1 row created.

//view all records currently in table


SQL> select *from tbl1;
EMPID EMPNAME EMPSALARY
---------- -------------------- ----------
106 hayes 12000
107 jhon 11000
108 smith 10000

Trigger types
1.statement level trigger
2.Row level trigger
1.STATEMENT LEVEL TRIGGER -DEMO
//trigger creation
SQL> create or replace trigger stmt_level_demo
2 before update
3 on tbl1
4 begin
5 DBMS_OUTPUT.PUT_LINE('Statement level Trigger executed');
6 end;
7 /
Trigger created.

//trigger execution
SQL> select *from tbl1;
EMPID EMPNAME EMPSALARY
---------- -------------------- ----------
106 hayes 12000
107 jhon 11000
108 smith 10000
//trigger output
SQL> update tbl1 set empname='william';
Statement level Trigger executed.3 rows updated.
------------------------------------------------------------------------------------------------------------
2.ROW LEVEL TRIGGER
//Example1
//trigger creation
SQL> create or replace trigger row_level_demo
2 before update
3 on tbl1
4 for each row
5 begin
6 DBMS_OUTPUT.PUT_LINE('Row Level trigger executed');
7 end;
8 /
Trigger created.

SQL> select *from tbl1;


EMPID EMPNAME EMPSALARY
---------- -------------------- ----------
106 william 12000
107 william 11000
108 william 10000
//trigger execution
SQL> update tbl1 set empname='hayes';
Trigger Fired Before Update//this is statement level triggger
Row Level trigger executed// below output for rowlevel triggers
Row Level trigger executed
Row Level trigger executed
3 rows updated.(note:both triggers are fired because we created 2triggers for single table)
Example2
ROW-LEVEL TRIGGGER DEMO(USING OLD AND NEW KEYWORD)
Table1:emp2
SQL> select *from emp2;
EMP_ID EMP_NAMESALARY
---------- ------------------
100 cse 1001
101 eee 5000

Table 2: employee_history
SQL>CREATE TABLE employee_history(emp_id NUMBER, emp_Name
VARCHAR2(20),salary NUMBER);
Table created.

SQL> desc employee_history;


Name Null? Type
-------------- -------- -
EMP_ID NUMBER
EMP_NAME VARCHAR2(20)
SALARY NUMBER

SQL> select *from employee_history;


no rows selected

//Trigger Creation
SQL> CREATE OR REPLACE TRIGGER salary_history_trigger
2 BEFORE UPDATE OF salary
3 ON emp2
4 FOR EACH ROW
5 BEGIN
6 INSERT INTO employee history VALUES (:old.emp_id,:old.emp_name,:old.salary);
7 END;
8 /
Trigger created.

//Trigger Execution
SQL> UPDATE emp2 SET salary=1500 WHERE emp_id=100;
1 row updated.

SQL> select *from employee_history;


EMP_ID EMP_NAME SALARY
--------------------------------------------
100 cse 1001

Note:When ever we update records in emp2 table,the old values of emp2 table are saved
into the emp_history by using triggers.
EX.NO 6 VIEWS AND INDEX

a) Simple View
- If a view is created based on single table
- It should not have any group function, aggregate function etc..

//create table
SQL> create table exp9_employees(empid number(5),empname varchar2(15),salary
int,mobileno number(10));
Table created.
SQL> desc exp9_employees;
Name Null? Type
--------------- -------- --------------
EMPID NUMBER(5)
EMPNAME VARCHAR2(15)
SALARY NUMBER(38)
MOBILENO NUMBER(10)

//record insertion
SQL> insert into exp9_employees values(100,'tamil',25000,9994392172);
1 row created.
SQL> insert into exp9_employees values(101,'vinoth',11000,9894383533);
1 row created.
SQL> insert into exp9_employees values(103,'ram',12000,9791069676);
1 row created.
SQL> insert into exp9_employees values(104,'kumar',14000,9999988888);
1 row created.
SQL> insert into exp9_employees values(105,'ananth',12000,9791067684);
1 row created.
SQL> insert into exp9_employees values(106,'arun',11000,9898756456);
1 row created.

//original table records


SQL> select *from exp9_employees;
EMPID EMPNAME SALARY MOBILENO
---------- --------------- ---------- ----------
100 tamil 25000 9994392172
101 vinoth 11000 9894383533
103 ram 12000 9791069676
104 kumar 14000 9999988888
105 ananth 12000 9791067684
106 arun 11000 9898756456

//view creation
SQL> create or replace view tempview1
2 as
3 select empid,empname from exp9_employees where empid in(100,101,103);
View created.
//view execution
SQL> select *from tempview1;
EMPID EMPNAME
---------- ---------------
100 tamil
101 vinoth
103 aravind

//view updation
SQL> update tempview1 set empname='kumar' where empid=100;
1 row updated.

//view records changed


SQL> select *from tempview1;
EMPID EMPNAME
---------- ---------------
100 kumar
101 vinoth
103 aravind
//original table records also changed
SQL> select *from exp9_employees;
EMPID EMPNAME SALARY MOBILENO
---------- --------------- ---------- ----------
100 kumar 25000 9994392172
101 vinoth 11000 9894383533
103 aravind 12000 9791069676
104 kumar 14000 9999988888
105 ananth 12000 9791067684
106 arun 11000 9898756456
6 rows selected.
//delete records from view
SQL> delete from tempview1 where empid=100;
1 row deleted.
//view table
SQL> select *from tempview1;
EMPID EMPNAME
---------- ---------------
101 vinoth
103 aravind
//orginal table
SQL> select *from exp9_employees;
EMPID EMPNAME SALARY MOBILENO
---------- --------------- ---------- ----------
101 vinoth 11000 9894383533
103 aravind 12000 9791069676
104 kumar 14000 9999988888
105 ananth 12000 9791067684
106 arun 11000 9898756456
b)complex views(use join condition inside view)
//create table with following structure and insert records
SQL> select *from exp9_employees;
EMPID EMPNAME SALARY MOBILENO DEPTID
---- --------------- ---------- ---------- ----------
100 tamil 25000 9994392172 105
101 vinoth 11000 9894383533 103
103 ram 12000 9791069676 100
104 kumar 14000 9999988888 109
105 ananth 12000 9791067684 109
106 arun 11000 9898756456 111
6 rows selected.

//normal selfjoin operation without view


SQL> select e1.empid,e1.empname,e2.mobileno,e2.deptid from exp9_employees
e1,exp9_employees e2 where e1.empid=e2.deptid order by deptid;
EMPID EMPNAME MOBILENO DEPTID
---------- --------------- ---------- ----------
100 tamil 9791069676 100
103 ram 9894383533 103
105 ananth 9994392172 105

//now convert the above self join operations into view(sef join execution with help of
view)
//COMPLEX VIEW CREATION
SQL> create or replace view cmpview1
2 as
3 select e1.empid,e1.empname,e2.mobileno,e2.deptid
4 from exp9_employees e1,exp9_employees e2
5 where e1.empid=e2.deptid order by deptid;
View created.

//complex view execution


SQL> select *from cmpview1;
EMPID EMPNAME MOBILENO DEPTID
---------- --------------- ---------- ----------
100 tamil 9791069676 100
103 ram 9894383533 103
105 ananth 9994392172 105

c)read only views


SQL> create or replace view tempview2
2 as
3 select empid,empname from exp9_employees
4 with read only;
View created.
//read only view execution
SQL> select *from tempview2;

EMPID EMPNAME
---------- ---------------
100 tamil
101 vinoth
103 ram
104 kumar
105 ananth
106 arun
5 rows selected.
//when update view,it shows error,bz its read only view
SQL> update tempview2 set empname='bala' where empid=100;
update tempview2 set empname='bala' where empid=100
ERROR at line 1:
ORA-42399: cannot perform a DML operation on a read-only view

//Drop a view from database


SQL> drop view tempview2;
View dropped.
-------------------------------------------------------------------------------------------------------------
INDEX. CREATION
SQL> create index temp1 on exp9_emp1(ename);
Index created.

//before index
SQL> select *from exp9_emp1;
EMPID ENAME JOB SALARY
---------- --------------- -------------------- ----------
100 tami hr 15000
101 anbu manager 12000
102 ramesh programmer 14000
103 jhon tester 13000
104 ashok leader 16000

//using index,search record


SQL> select *from exp9_emp1 where ename='jhon';
EMPID ENAME JOB SALARY
---------- --------------- -------------------- ----------
103 jhon tester 13000

NOTE: we can check difference between normal execution and index execution answers if
we insert more than 100 records. Time delay will get reduce if we use,index concepts.
EX.NO7 USER DEFINED FUNCTIONS AND PROCEDURES IN
ORACLE

//PROCEDURES DEMO
//EXAMPLE1 //PROCEDURE CREATION
SQL> create procedure si29(p number, n number, r number)
2 is s number;
3 begin
4 s:=(p*n*r)/100;
5 dbms_output.put_line('SI='||s);
6 end;
7/
Procedure created.

//PROCEDURE CALLING
SQL> declare p number:=&p;
2 n number:=&n;
3 r number:=&r;
4 begin
5 si29(p,n,r);
6 end;
7/

//Output
Enter value for p: 1000
old 1: declare p number:=&p;
new 1: declare p number:=1000;

Enter value for n: 3


old 2: n number:=&n;
new 2: n number:=3;

Enter value for r: 2


old 3: r number:=&r;
new 3: r number:=2;

SI=60
PL/SQL procedure successfully completed.
---------------------------------------------------------------------------------------------------------------
//EXAMPLE 2
//CREATIONS OF PROCEUDRE
SQL>CREATE OR REPLACE PROCEDURE welcome_msg (p_name IN VARCHAR2)
IS
BEGIN
dbms_output.put_line ("Welcome"||p_name);
END;
/

//EXECUTION OF PROCEDURE SIMPLE METHOD


SQL>EXEC welcome_msg ("Guru99");

//Ouput
welcome Guru99
//EXAMPLE 3
//CREATION OF PROCEDURES FOR TABLES AND READ TABLE VALUES

//CREATE TABLE
SQL> create table ititems(itemid number(3), actualprice number(5), ordid number(4),
prodid number(4)); Table created.

//INSERT 4RECORDS
SQL> insert into ititems values(101, 2000, 500, 201);
1 row created.
SQL> insert into ititems values(102, 3000, 1600, 202);
1 row created.
SQL> insert into ititems values(103, 4000, 600, 202);
1 row created.

SQL> select * from ititems;


ITEMID ACTUALPRICE ORDID PRODID
--------- ----------- -------- ---------
101 2000 500 201
102 3000 1600 202
103 4000 600 202

//PROCEDURE FOR ‘IN’ PARAMETER – CREATION, EXECUTION


SQL> create procedure procedurename1(a IN number) is price number;
2 begin
3 select actualprice into price from ititems where itemid=a;
4 dbms_output.put_line('Actual price is ' || price);
5 if price is null then
6 dbms_output.put_line('price is null');
7 end if;
8 end;
9 / Procedure created.

//execution procedure
SQL> exec procedurename1(103);

//OUTPUT:
Actual price is 4000
PL/SQL procedure successfully completed.
--------------------------------------------------------------------------------------------------------------
//EXAMPLE4 //PROCEDURE FOR ‘OUT’ PARAMETER – CREATION,
EXECUTION
SQL> set serveroutput on;

//procedure creation
SQL> create procedure zzz (a in number, b out number) is identity number;
2 begin
3 select ordid into identity from ititems where itemid=a;
4 if identity<1000 then
5 b:=100;
6 end if;
7 end;
8 / Procedure created.
//CALLING PROCEDURE FROM CALLER PROGRAM
SQL> declare
2 a number;
3 b number;
4 begin
5 zzz(101,b);
6 dbms_output.put_line('The value of b is '|| b);
7 end;
8/
OUTPUT
The value of b is 100
PL/SQL procedure successfully completed.
------------------------------------------------------------------------------------------------
//PROCEDURE FOR ‘INOUT’ PARAMETER – CREATION, EXECUTION
//EXAMPLE5
//procedure creation
SQL> create procedure itit( a in out number) is begin
2 a:=a+1;
3 end;
4/
Procedure created.

//calling procedure
SQL> declare
2 a number:=7;
3 begin
4 itit(a);
5 dbms_output.put_line('The updated value is '||a);
6 end;
7/
OUTPUT
The updated value is 8
PL/SQL procedure successfully completed.
-----------------------------------------------------------------------------------------------------------
FUNCTION CREATION DEMO
//Example1//CREATION FUNCTIONS
SQL> create or replace function facto29 (n number)
2 return number is a number;
3 f number:=1;
4 begin
5 for i in 1..n loop
6 f:=f*i;
7 end loop;
8 return f;
9 end;
10 /
Function created.
//FUNCTION CALLING
SQL> declare n number:=&n;
2 a number;
3 begin
4 a:=facto29(n);
5 dbms_output.put_line('factorial = '||a);
6 end;
7/

Enter value for n: 5


old 1: declare n number:=&n; new 1: declare n number:=5;
factorial = 120PL/SQL procedure successfully completed.

//EXAMPLE2
//FUNCTION CREATION(DEMO2)
SQL> CREATE OR REPLACE FUNCTION welcome_msgJune(p_name IN
VARCHAR2)RETURN VARCHAR2
2 is
3 begin
4 return('welcome'||p_name);
5 end;
6 /
Function created.

//FUNCTION CALLING
SQL> declare
2 lv_msg varchar2(50);
3 begin
4 lv_msg:=welcome_msgjune('guru99');
5 dbms_output.put_line(lv_msg);
6 end;
7/
output
welcome guru99
PL/SQL procedure successfully completed.

//CALLING FUNCTION USING SELECT STATEMENT)


SQL> select welcome_msgjune('guru100’) from dual;
WELCOME_MSGJUNE('GURU100')
welcomeguru100
EX.NO 8 DOCUMENT BASED DB CREATION USING MONGODB

What is MongoDB?
➢ MongoDB is an open source platform written in C++ and has a very easy setup
environment.
➢ It is a cross-platform, document-oriented and non-structured database.
MongoDB provides high performance, high availability, and auto-scaling.
➢ It is a NoSQL database and has flexibility with querying and indexing. MongoDB
has very rich query language resulting in high performance.

FEATURES OF MONGODB
• Indexing: Indexes are used to boost the performance of queries.
• Schemaless: This feature makes it a flexible database to query any depth of
Document nesting.
• Sharding(Dividing and store): Using Sharding MongoDB, distribute the
big datasets over multiple nodes for high throughputs.
• Replication: Through Replication the copy of data is replicated over
multiple nodes to provide high redundancy.

CRUD OPERATIONS IN MONGODB

• CREATE:- The MongoDB CREATE operation is used to create a new


Document in the Collection.
• READ:- The MongoDB READ operation is used to fetch the records from
the Collection.
• UPDATE:- The MongoDB UPDATE operation is used to modify the
existing Documents in the Collection.
• DELETE:- The MongoDB DELETE operation is used to delete the existing
Documents from the Collection.
//open mongodb shell and execute the following commands

//show existing mongodb databases


test> show dbs
admin 40.00 KiB
config 12.00 KiB
local 72.00 KiB
--------------------------------------------------------------------------------
//create our own database (gcecse)
test> use gcecse
switched to db gcecse
gcecse> db
gcecse
---------------------------------------------------------------
//create collections to gcecse database
gcecse> db.createCollection("students")
{ ok: 1 }
--------------------------------------------------------------------
1.Insert operations
gcecse> db.students.insertOne({"rollno":1,"name":"hayes"})
{
acknowledged: true,
insertedId: ObjectId("6465c42a20ff566800ba8a9d")
}

//insert another document into collection


gcecse> db.students.insertOne({"rollno":2,"name":"jhon"})
gcecse> db.students.insertOne({"rollno":3,"name":"william"})

//now view available databases


gcecse> show dbs
admin 40.00 KiB
config 92.00 KiB
gcecse 8.00 KiB
local 72.00 KiB

//to view our collections


gcecse> show collections
students

2.Read Operations(select )
//to view documents from collections
gcecse> db.students.find() or //db.students.find().pretty()
[
{
_id: ObjectId("6465c42a20ff566800ba8a9d"),
rollno: 1,
name: 'hayes'
},
{
_id: ObjectId("6465ca1820ff566800ba8a9e"),
rollno: 2,
name: 'jhon'
},
{
_id: ObjectId("6465ca7320ff566800ba8a9f"),
rollno: 3,
name: 'william'
}]

//find single student from document


gcecse> db.students.find({name:"jhon"})
[
{
_id: ObjectId("6465ca1820ff566800ba8a9e"),
rollno: 2,
name: 'jhon'
}]

//filter only rollno 2 students


gcecse> db.students.find({rollno:2})
[
{
_id: ObjectId("6465ca1820ff566800ba8a9e"),
rollno: 2, name: 'jhon'
}]

//using some conditions filter documents


//return results who roll no is greater than 2(answer only rollno3)
gcecse> db.students.find({rollno:{$gt:2}})
[
{
_id: ObjectId("6465ca7320ff566800ba8a9f"),
rollno: 3,
name: 'william'
}]

//based on condition returns student name only(who rollno greater than1)


gcecse> db.students.find({rollno:{$gt:1}},{_id:false,name:true})
[ { name: 'jhon' }, { name: 'william' } ]

//based on condition show student rollno,name//hide display id


gcecse> db.students.find({rollno:{$gt:1}},{_id:false,rollno:true,name:true})
[ { rollno: 2, name: 'jhon' }, { rollno: 3, name: 'william' } ]
//find single column values i.e students name only
gcecse> db.students.find({},{_id:false,name:true})
[ { name: 'hayes' }, { name: 'jhon' }, { name: 'william' } ]

//to view documents in ascending or descending order//ascending order


gcecse> db.students.find().sort({name:1})
[
{
_id: ObjectId("6465c42a20ff566800ba8a9d"),
rollno: 1,
name: 'hayes'
},
{
_id: ObjectId("6465ca1820ff566800ba8a9e"),
rollno: 2,
name: 'jhon'
},
{
_id: ObjectId("6465ca7320ff566800ba8a9f"),
rollno: 3,
name: 'william'
}
]
//descending order
gcecse> db.students.find().sort({name:-1})
[
{
_id: ObjectId("6465ca7320ff566800ba8a9f"),
rollno: 3,
name: 'william'
},
{
_id: ObjectId("6465ca1820ff566800ba8a9e"),
rollno: 2,
name: 'jhon'
},
{
_id: ObjectId("6465c42a20ff566800ba8a9d"),
rollno: 1,
name: 'hayes'
}
]
3.Update operations
//before update view all the documents from collections
gcecse> db.students.find()
[
{
_id: ObjectId("6465c42a20ff566800ba8a9d"),
rollno: 1,
name: 'hayes'
},
{
_id: ObjectId("6465ca1820ff566800ba8a9e"),
rollno: 2,
name: 'jhon'
},
{
_id: ObjectId("6465ca7320ff566800ba8a9f"),
rollno: 3,
name: 'william'
}
]

//update student name from william to arun for rollno 3


gcecse> db.students.updateOne({rollno:3},{$set:{name:"arun"}})
{
acknowledged: true,
insertedId: null,
matchedCount: 1,
modifiedCount: 1,
upsertedCount: 0
}

//after update documents view documents


gcecse> db.students.find()
[
{
_id: ObjectId("6465c42a20ff566800ba8a9d"),
rollno: 1,
name: 'hayes'
},
{
_id: ObjectId("6465ca1820ff566800ba8a9e"),
rollno: 2,
name: 'jhon'
},
{
_id: ObjectId("6465ca7320ff566800ba8a9f"),
rollno: 3,
name: 'arun'
}]

//4.Delete operations
//before deletion documents
gcecse> db.students.find()
[
{
_id: ObjectId("6465c42a20ff566800ba8a9d"),
rollno: 1, name: 'hayes'
},
{ _id: ObjectId("6465ca1820ff566800ba8a9e"),
rollno: 2, name: 'jhon'
},
{ _id: ObjectId("6465ca7320ff566800ba8a9f"),
rollno: 3, name: 'arun'
}
]

//now delete rollno2 from collections


gcecse> db.students.deleteOne({rollno:2})
{ acknowledged: true, deletedCount: 1 }

//after deletion
gcecse> db.students.find()
[
{
_id: ObjectId("6465c42a20ff566800ba8a9d"),
rollno: 1, name: 'hayes'
},
{
_id: ObjectId("6465ca7320ff566800ba8a9f"),
rollno: 3, name: 'arun'
}
]
//deletion based on name column
gcecse> db.students.deleteOne({name:"arun"})
{ acknowledged: true, deletedCount: 1 }
gcecse> db.students.find()
[
{ _id: ObjectId("6465c42a20ff566800ba8a9d"),
rollno: 1, name: 'hayes
}
]
MongoDB Distributed System Architecture
EX.NO 9 DATABASE CONNECTION FOR WINDOWS APPLICATION

Aim:
To Create Real Life Database applications and demonstrate database connection.

PROCEDURE TO CONNECT DATABASE WITH FRONTEND GUI


1.Design Database with tables
2.Design FrontEnd (GUI) with necessary properties
3.Write individual button click event handler code with namespace

Key Classes in ADO.NET


The Knowledge class offers methods for packing and performing SQL statements and
Stored Actions.
1) Connection Class 2) Command Class 3) DataReader Class
4) DataAdaptor Class 5) DataSet.Class

Description for the above Classes:

1. Connection Class
We use connection classes to link to the database.
These connection classes similarly manage connections and connection pooling in
ADO.NET.

Example:
SqlConnection con = new
SqlConnection(ConfigurationManager.ConnectionStrings[“connection”].Connection
String);
con.Open();


con.Close();
2. Command Class
Various commands that are executed by the Command Class.
The Command class deliver methods for storing and executing SQL statements and Stored
Actions. Such as.

ExecuteReader():
Typically be an SQL select statement that covers one or more select statements and Stored
Procedures. This technique returns a DataReader object that can be used to fill a DataTable
object or used straight for production reports and so forth.
ExecuteNonQuery():
This method returns an integer that is the sum of rows affected by the query.
Performs a command that variations the data in the database, such as an update, delete, or
insert statement, or a Kept Way that covers one or more of these statements.
ExecuteScalar():
Its a kind of query returns a total count of rows or an intended value. This method
returns a single value only.
ExecuteXMLReader: Obtains data from an SQL Server 2000 database (SqlClient classes
only) using the XML stream. And Returns an XML Reader object.
3. DataReader Class()
✓ DataReader class is used in the conjunction with the Command class that performs
an SQL Select statement and then access resumed rows.
✓ The DataReader major operation is used to retrieve data.

4. DataAdapter Class
✓ The DataAdapter is supremely useful when consuming data-bound controls in the
Windows Forms, but it can likewise be used to bring an easy way to accomplish the
connection in between your application and core database tables, views and Stored
Procedures.
✓ The major job of the DataAdapter is to connect the DataSets to databases.

5. DataSet Class
✓ DataSet is essentially a collection of DataTable objects. In turn, each object contains
a group of the DataColumn and DataRow objects.
✓ DataSet also shields a kindred collection that can be used to label relations among
Data Table Objects. The DataSet is the core of ADO.NET.

//Procedure to execution
//CONNECT TO DATABASE(userid :sa password: cse)

CREATE TABLE STUDENT WITH ROLLNO,STUDENTNAME,AGE,COURSE


FrontEnd (GUI Form Design)

//SOURCE CODE
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient; //add this namespace

namespace test1
{
public partial class Form1 : Form
{
public Form1()
{

InitializeComponent();
}

//global declaration of connection strings


SqlConnection conn;
SqlCommand comm;
SqlDataReader dreader;
string connstring = "server=localhost; database=college; user=sa; password=cse";

//SAVE BUTTON CODE


private void btnsave_Click(object sender, EventArgs e)
{
conn = new SqlConnection(connstring);
conn.Open();
comm = new SqlCommand("insert into student values(" + txtrno.Text + " ,' " +
txtsname.Text + " ', " + txtage.Text + " ,' " + txtcoursename.Text + " ') ", conn);
try
{ comm.ExecuteNonQuery();
MessageBox.Show("Record Saved Successful...");
}
catch (Exception)
{ MessageBox.Show("Not Saved");
}
finally
{ conn.Close();
}
}

//CLEAR BUTTON CODE


private void button1_Click(object sender, EventArgs e)
{
txtrno.Clear(); txtsname.Clear();
txtage.Clear(); txtcoursename.Clear();
txtrno.Focus(); }

//SEARCH BUTTON CODE


private void btnsearch_Click(object sender, EventArgs e)
{
conn = new SqlConnection(connstring);
conn.Open();
comm = new SqlCommand("select * from student where rollno = " + txtrno.Text + " ",
conn);
try
{
dreader = comm.ExecuteReader(); if
(dreader.Read())
{
txtsname.Text = dreader[1].ToString(); txtage.Text
= dreader[2].ToString(); txtcoursename.Text =
dreader[3].ToString();
}
else
{
MessageBox.Show(" No Record");
}
dreader.Close();
}
catch (Exception)
{
MessageBox.Show(" No Record");
}
finally
{ conn.Close();
} }

//UPDATE BUTTON CODE


private void btnupdate_Click(object sender, EventArgs e)
{
conn = new SqlConnection(connstring);
conn.Open();
comm = new SqlCommand("update student set studentname= '" + txtsname.Text + "',age=
" + txtage.Text + " ,course=' " + txtcoursename.Text + "' where rollno ="+txtrno.Text+" ",
conn);
try
{
comm.ExecuteNonQuery();
MessageBox.Show("Updated..");
}
catch (Exception)
{
MessageBox.Show(" Not Updated");
}
finally
{
conn.Close();
}
}

//DELETE BUTTON CODE


private void btndelete_Click(object sender, EventArgs e)
{
conn = new SqlConnection(connstring);
conn.Open();
comm = new SqlCommand("delete from student where rollno = " + txtrno.Text + "
", conn);
try
{
comm.ExecuteNonQuery();
MessageBox.Show("Deleted...");
txtage.Clear(); txtcoursename.Clear();
txtsname.Clear();
txtrno.Clear();
txtrno.Focus();
}
catch (Exception x)
{
MessageBox.Show(" Not Deleted" + x.Message);
}
finally
{
conn.Close();
}
}
}
}
OUTPUT
//INSERT RECORD

//UPDATE RECORD
// DELETE RECORDS

//SEARCH RECORDS

Result:
Thus Real Life Database applications is Created and Performed CRUD operations.
EX.NO10 CREATE XML DATABASE AND VALIDATE USING XML
SCHEMA
Aim:
Create xml database and validate the xml db file using DTD or Schema.

XML DATA BASE VALIDATION PROCEDURE

Need for validating XML Document(check valid xml and well formed xml)
✓ XML validation is a process done to check for a syntax error in an XML document
to ensure that the document is well-written with the standard rules using either DTD
or schema.
✓ A complete XML file is considered to be valid XML document unless it has correct
syntax and constraints defined in it.
✓ Validation Process is dealt with XML Parser in two different ways.One is Well-
defined XML Document and another one is Valid XML Document.
✓ Validation is optional but when it is about data integrity it is highly recommended.
✓ In most of the cases, validation of XML is done through schemas, not by DTD.

What is an XSD file.( https://www.youtube.com/watch?v=SGVL_SIYIGA)

An XSD ( XML Schema Definition Language) file defines the structure of the XML file, i.e
which elements in which order, how many times, with which attributes, how they are nested,
etc. Without an XSD, an XML file is a relatively free set of elements and attributes.

Structure of the Project(create console c# application and add xsd file and xml file)

Steps to validate an XML file using XSD file


Step 1 : Create a new Console application. Name it Demo.
Step 2 : Add a new XML Schema file to the project. Name it Student.xsd. Copy and paste the
following XML.

Student.xsd(schema file)
<?xml version="1.0" encoding="utf-8"?>
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<xsd:element name="Students">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="Student" minOccurs="1" maxOccurs="4">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="Name" minOccurs="1" maxOccurs="1"/>
<xsd:element name="Gender" minOccurs="1" maxOccurs="1"/>
<xsd:element name="TotalMarks" minOccurs="1" maxOccurs="1"/>
</xsd:sequence>
</xsd:complexType>
</xsd:element>
</xsd:sequence>
</xsd:complexType>
</xsd:element>
</xsd:schema>

The above XSD specifies that


1. The root element must be Students
2. Students root element should contain at least 1 Student element. More than 4 Student
elements are not allowed.

3. Each Student element should contain the following 3 elements in the order specified.
i) Name
ii) Gender
iii) TotalMarks

Step 3: Add a new XML file to the project. Name it Data.xml. Copy and paste the following
XML.

//data.xml(xml database file)


<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<Students>
<Student>
<Name>Mark</Name>
<Gender>Male</Gender>
<TotalMarks>800</TotalMarks>
</Student>
<Student>
<Name>Rosy</Name>
<Gender>Female</Gender>
<TotalMarks>900</TotalMarks>
</Student>
<Student>
<Name>Pam</Name>
<Gender>Female</Gender>
<TotalMarks>850</TotalMarks>
</Student>
<Student>
<Name>John</Name>
<Gender>Male</Gender>
<TotalMarks>950</TotalMarks>
</Student></Students>
Step 4 : To validate Data.xml against Student.xsd file, copy and paste the following code in
the Main() method.

(CREATE CONSOLE APPLICATION USING C# IN VS2015)


//add the following name spaces
using System;
using System.Linq;
using System.Xml.Linq;
using System.Xml.Schema;

//code for validate the xml file


XmlSchemaSet schema = new XmlSchemaSet();
schema.Add("", @"C:\Demo\Demo\Student.xsd");
XDocument xmlDocument = XDocument.Load(@"C:\Demo\Demo\Data.xml");
bool validationErrors = false;
xmlDocument.Validate(schema, (s, e) =>
{
Console.WriteLine(e.Message);
validationErrors = true;
});
if (validationErrors)
{
Console.WriteLine("Validation failed");
}
else
{
Console.WriteLine("Validation succeeded");
}

OUTPUT

IF WE REMOVE ANY ELEMENT FROM XML FILE ,IT THROWS ERROR

Result:
Thus the xml database is created and validated using xml schema.

You might also like