CS3481 Database Management Lab Syllabus
CS3481 Database Management Lab Syllabus
BE CSE IV SEMESTER
PERI Institute of Technology
Department of Computer Science and Engineering
Vision:
Mission:
In the process of realization of its Vision, PERIIT strives to provide quality technical
education at affordable cost in a challenging & stimulating environment with state-of-the-art facilities
and a global team of dedicated and talented academicians, without compromising in its core values
of honesty, transparency and excellence.
Vision:
The vision of the department is to prepare industry-ready competent professionals with moral
values by imparting scientific knowledge and skill-based education.
Mission:
• To provide exposure of latest tools and technologies in the broad area of computing.
• To promoter search-based projects/activities in the emerging area soft technology.
• ToenhanceIndustryInstituteInteractionprogramtogetacquaintedwithcorporateculture
and to develop entrepreneurship skills.
• To induce ethical values and spirit of social commitment.
PROGRAM OUTCOMES (POs)
2 Problem analysis: Identify, formulate, review research literature, and analyze complex
engineering problems reaching substantiated conclusions using first principles of
mathematics, natural sciences, and engineering sciences.
5 Modern tool usage: Create, select, and apply appropriate techniques, resources, and
modern engineering and IT tools including prediction and modeling to complex engineering
activities with an understanding of the limitations.
6 The engineer and society: Apply reasoning informed by the contextual knowledge to
assess societal, health, safety, legal and cultural issues and the consequent responsibilities
relevant to the professional engineering practice.
8 Ethics: Apply ethical principles and commit to professional ethics and responsibilities and
norms of the engineering practice.
12 Life-long learning: Recognize the need for, and have the preparation and ability to
engage in independent and life-long learning in the broadest context of technological change.
CS3481 DATABASE MANAGEMENT SYSTEMS LABORATORY LTPC
0 0 3 1.5
COURSE OBJECTIVES:
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
aggregate functions.
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
● Build Entity Model diagram. The diagram should align with the business and functional
goals stated in the application.
● Apply Normalization rules in designing the tables in scope.
● Prepared applicable views, triggers (for auditing purposes), functions for enabling
enterprise grade features.
● Build PL SQL / Stored Procedures for Complex Functionalities, ex EOD Batch Processing
for calculating the EMI for Gold Loan for each eligible Customer.
● Ability to showcase ACID Properties with sample queries with appropriate settings
TOTAL: 45 PERIODS
COURSE OUTCOMES:
At the end of this course, the students will be able to:
CO1: Create databases with different types of key constraints.
CO2: Construct simple and complex SQL queries using DML and DCL commands.
CO3: Use advanced features such as stored procedures and triggers and incorporate in GUI based
application development.
CO4: Create an XML database and validate with meta-data (XML schema).
CO5: Create and manipulate data using NOSQL database
Ex.No : 1 DDL & DML Commands
Create a database table, add constraints (primary key, unique, check, Not null), insert
rows,update and delete rows using SQL DDL and DML commands.
AIM:
To perform various DDL & DML commands and implement them on the database.
DDL COMMANDS
1. The Create Table Command: - it defines each column of the table uniquely. Each column
has minimum of three attributes, a name , data type and size.
Syntax:
Create table <table name> (<col1> <datatype>(<size>),<col2> <datatype><size>));
7. Destroying tables.
Syntax:
Drop table <tablename>;
EXAMPLE:
Table created.
1 row created.
1 row created.
OUTPUT:
Select * from std;
Table created.
1 row created.
SYNTAX:
EXAMPLE:
SQL>alter table student add(age number(4));
OUTPUT:
ALTER: select * from student;
ID NAME GAME
1 Mercy Cricket
1 Mercy cricket
2 Sharmi Tennis 19
SYNTAX:
Alter table<tablename>modify(col1 datatype,col2 datatype..);
EXAMPLE:
OUTPUT:
MODIFY
desc student;
Id Number(6)
Name Varchar(20)
Game Varchar(25)
Age Number(4)
DROP:
SYNTAX: drop table<tablename>;
EXAMPLE:
SQL>Table dropped.
TRUNCATE TABLE
DESC
EName VarChar(15)
DML COMMANDS
DML commands are the most frequently used SQL commands and is used to query
and manipulate the existing database objects. Some of the commands are Insert, Select,
Update, Delete.
Insert Command This is used to add one or more rows to a table. The values are separated by
commas and the data types char and date are enclosed in apostrophes. The values must be
entered in the same order as they are defined.
Select Commands It is used to retrieve information from the table. It is generally referred to
as querying the table. We can either display all columns in a table or only specify column
from the table.
Update Command It is used to alter the column values in a table. A single column may be
updated or more than one column could be updated.
Delete command After inserting row in a table we can also delete them if required. The delete
command consists of a from clause followed by an optional where clause.
Q1: Insert a single record into dept table.
1 row created.
Q2: Insert more than a record into emp table using a single insert command.
1 row created.
1 row created.
1 row created.
Q3: Update the emp table to set the salary of all employees to Rs15000/- who are working as
ASP
1 Mathi AP 1 10000
1 Mathi AP 1 10000
Q4: Create a pseudo table employee with the same structure as the table emp and insert rows
into the table using select clauses.
Table created.
EMPNO NUMBER(6)
DEPTNO NUMBER(3)
SAL NUMBER(7,2)
Mathi AP
Arjun ASP
Gugan ASP
Karthik Prof
Akalya AP
suresh lect
6 rows selected.
Q6: Delete only those who are working as lecturer
Ans: SQL> select * from emp;
EMPNO ENAME JOB DEPTNO SAL
1 Mathi AP 1 10000
2 Arjun ASP 2 15000
3 Gugan ASP 1 15000
4 Karthik Prof 2 30000
5 Akalya AP 1 10000
6 suresh lect 1 8000
6 rows selected.
SQL> delete from emp where job='lect';
1 row deleted.
SQL> select * from emp;
EMPNO ENAME JOB DEPTNO SAL
-
1 Mathi AP 1 10000
2 Arjun ASP 2 15000
3 Gugan ASP 1 15000
4 Karthik Prof 2 30000
5 Akalya AP 1 10000
Q7: List the records in the emp table orderby salary in ascending order.
Ans: SQL> select * from emp order by sal;
EMPNO ENAME JOB DEPTNO SAL
1 Mathi AP 1 10000
5 Akalya AP 1 10000
2 Arjun ASP 2 15000
3 Gugan ASP 1 15000
4 Karthik Prof 2 30000
Q8: List the records in the emp table orderby salary in descending order.
Ans: SQL> select * from emp order by sal desc;
EMPNO ENAME JOB DEPTNO SAL
1 Mathi AP 1 10000
3 Gugan ASP 1 15000
5 Akalya AP 1 10000
Q10: Display deptno from the table employee avoiding the duplicated values.
Solution:
1. Use SELECT FROM syntax.
2.Select should include distinct clause for the deptno.
Ans: SQL> select distinct deptno from emp;
DEPTNO
RESULT:
Thus the DDL & DML commands have been executed successfully.
Ex.No: 2 Constraints
Create a set of tables, add foreign key constraints and incorporate referential integrity.
Aim:
To execute and verify the various constraints in set of tables.
CONSTRAINTS:
Create table tablename (column_name1 data_ type constraints, column_name2 data_ type
constraints …)
Example:
Create table Emp ( EmpNo number(5), EName VarChar(15), Job Char(10) constraint un
unique, DeptNo number(3) CONSTRAINT FKey2 REFERENCES DEPT(DeptNo));
Create table stud (sname varchar2(20) not null, rollno number(10) not null,dob date not null);
DOMAIN INTEGRITY
CHECK CONSTRAINT
Example: Create table student (regno number (6), mark number (3) constraint b check (mark
>=0 and mark <=100)); Alter table student add constraint b2 check (length(regno<=4));
ENTITY INTEGRITY
Queries:
Q1. Create a table called EMP with the following structure.
Name Type
Q3: Modify the column width of the job field of emp table.
Solution:
1. Use the alter table syntax.
2. Modify the column width and its data type.
Ans: SQL> alter table emp modify(job varchar2(12));
Table altered.
DEPTNO NUMBER(2)
DNAME VARCHAR2(10)
LOC VARCHAR2(10)
Deptno as the primarykey
Solution:
1. Understand create table syntax.
2. Decide the name of the table.
3. Decide the name of each column and its data type.
4. Use the create table syntax to create the said tables.
5. Create primary key constraint for each table as understand from logical table structure.
Ans:
SQL> create table dept(deptno number(2) primary key,dname varchar2(10),loc
varchar2(10));
Table created.
Q5: create the emp1 table with ename and empno, add constraints to check the empno value
while entering (i.e) empno > 100.
Solution:
1. Learn alter table syntax.
2. Define the new constraint [columns name type]
3. Use the alter table syntax for adding constraints.
Ans:
SQL> create table emp1(ename varchar2(10),empno number(6) constraint
check(empno>100));
Table created.
Q7: Truncate the emp table and drop the dept table
Solution:
RESULT:
Query the database tables using different ‘where’ clause conditions and also implement
aggregate functions.
Aim:
To query the table using aggregate function & different where clause
1 row created.
Q2: Insert more than a record into emp table using a single insert command.
1 row created.
1 row created.
1 row created.
Q3: Update the emp table to set the salary of all employees to Rs15000/- who are working as
ASP
1 Mathi AP 1 10000
1 Mathi AP 1 10000
Table created.
DEPTNO NUMBER(3)
SAL NUMBER(7,2)
Mathi AP
Arjun ASP
Gugan ASP
Karthik Prof
Akalya AP
suresh lect
6 rows selected.
Q6: Delete only those who are working as lecturer
Ans: SQL> select * from emp;
EMPNO ENAME JOB DEPTNO SAL
1 Mathi AP 1 10000
2 Arjun ASP 2 15000
3 Gugan ASP 1 15000
4 Karthik Prof 2 30000
5 Akalya AP 1 10000
6 suresh lect 1 8000
6 rows selected.
SQL> delete from emp where job='lect';
1 row deleted.
SQL> select * from emp;
EMPNO ENAME JOB DEPTNO SAL
-----------------
1 Mathi AP 1 10000
2 Arjun ASP 2 15000
3 Gugan ASP 1 15000
4 Karthik Prof 2 30000
5 Akalya AP 1 10000
Q7: List the records in the emp table orderby salary in ascending order.
Ans: SQL> select * from emp order by sal;
EMPNO ENAME JOB DEPTNO SAL
1 Mathi AP 1 10000
5 Akalya AP 1 10000
2 Arjun ASP 2 15000
3 Gugan ASP 1 15000
4 Karthik Prof 2 30000
Q8: List the records in the emp table orderby salary in descending order.
Ans: SQL> select * from emp order by sal desc;
EMPNO ENAME JOB DEPTNO SAL
1 Mathi AP 1 10000
3 Gugan ASP 1 15000
5 Akalya AP 1 10000
Q10: Display deptno from the table employee avoiding the duplicated values.
Solution:
1. Use SELECT FROM syntax.
2.Select should include distinct clause for the deptno.
Ans: SQL> select distinct deptno from emp;
DEPTNO
CHARACTER/STRING FUNCTION:
---
HAI
LOW
---
hai
INITCAP('Hello
Hello World
LTR
---
hai
---
hai
RTRIM('
hai
SQL> select concat('Anna',' university')from dual;
Anna university
LENGTH('SRM')
12
Anna university
SUBSTR
lingam
SQL> select rpad('hai',3,'*')from dual;
RPAD('
hai***
LPAD('
***hai
REPLACE
Danie
SQL> select translate('cold','ld','ol')from dual;
TRANSL
cool
DATE & TIME FUNCTION
07-APR-10
07-APR-10
07-JUL-10
30-APR-10
27-APR-10
NEXT_DAY(
13-APR-10
NUMERIC FUNCTION
16
24
34
15
-1
ABS(-70)
70
MATH FUNCTION:
ABS(45)
45
POWER(10,12)
1.000E+12
MOD(11,5)
EXP(10)
22026.466
SQRT(225)
15
Result
Thus quering the table using aggregate function & different where clause are executed successfully.
Ex.No:4 Sub Queries
Aim : To Query the database tables and explore sub queries and simple join operations.
Q1: Display all employee names and salary whose salary is greater than minimum salary of
the company and job title starts with ‗M‘.
Solution:
2. Use like operator to match job and in select clause to get the result.
Ans: SQL> select ename,sal from emp where sal>(select min(sal) from emp where job like
'A%');
ENAME SAL
Arjun 12000
Gugan 20000
Karthik 15000
Q2: Issue a query to find all the employees who work in the same job as Arjun.
1 Mathi AP 1 10000
4 Karthik AP 1 15000
SQL> select ename from emp where job=(select job from emp where ename='Arjun');
ENAME
Arjun
Gugan
SET OPERATORS
Q1: Display all the dept numbers available with the dept and emp tables avoiding duplicates.
Solution:
Ans: SQL> select deptno from emp union select deptno from dept;
DEPTNO
12
30
40
Q2: Display all the dept numbers available with the dept and emp tables.
Solution:
Ans: SQL> select deptno from emp union all select deptno from dept;
DEPTNO
2
1
12
30
40
9 rows selected.
Q3: Display all the dept numbers available in emp and not in dept tables and vice versa.
Solution:
Ans: SQL> select deptno from emp minus select deptno from dept;
DEPTNO
12
SQL> select deptno from dept minus select deptno from emp;
DEPTNO
30
40
Result:
Aim:
To perform various join operation in database
NESTED QUERIES AND JOIN QUERIES
Q1: Display all employee names and salary whose salary is greater than minimum salary of
the company and job title starts with ‗M‘.
Solution:
4. Use like operator to match job and in select clause to get the result.
Ans: SQL> select ename,sal from emp where sal>(select min(sal) from emp where job like
'A%');
ENAME SAL
Arjun 12000
Gugan 20000
Karthik 15000
Q2: Issue a query to find all the employees who work in the same job as Arjun.
5 Mathi AP 1 10000
8 Karthik AP 1 15000
SQL> select ename from emp where job=(select job from emp where ename='Arjun');
ENAME
Arjun
Gugan
Q3: Issue a query to display information about employees who earn more than any employee
in dept 1. Ans: SQL> select * from emp where sal>(select max(sal) from emp where
empno=1); EMPNO ENAME JOB DEPTNO SAL
1 Mathi AP 1 10000
2 Arjun ASP 2 12000
3 Gugan ASP 2 20000
4 Karthik AP 1 15000
SQL> select * from dept;
DEPTNO DNAME LOC
Q4: Display the employee details, departments that the departments are same in both the emp
and dept. Solution: 1. Use select from clause.
2. Use equi join in select clause to get the result.
Ans: SQL> select * from emp,dept where emp.deptno=dept.deptno;
EMPNO ENAME JOB DEPTNO SAL DEPTNO DNAME LOC
john 89 80 pass
101 Raja 70 80 pass
102 Sharin 70 90 pass
103 sam 90 95 pass
john s raj
s sam a sharin a smith null
RIGHTOUTER-JOIN
Q7: Display the Student name, register no, and result by implementing a right outer join.
Ans: SQL> select stud1.name, regno, result from stud1 right outer join stud2 on stud1.name
= stud2.name; Name Regno Result
1 sindu 90 95 185
2 arul 90 90 180
FULLOUTER-JOIN
Q8: Display the Student name register no by implementing a full outer join.
Ans: SQL> select stud1.name, regno from stud1 full outer join stud2 on (stud1.name=
stud2.name); Name Regno
john 101
raj 102 sam
103 sharin 104
SELFJOIN
Arjun
Gugan
Karthik
Mathi
Q10: Display the details of those who draw the salary greater than the average salary.
Ans: SQL> select distinct * from emp x where x.sal >= (select avg(sal) from emp);
EMPNO ENAME JOB DEPTNO SAL
Result:
Table created.
1 row created.
1 row created.
ID FIRST_NAME
101 Nithya
102 Maya
5 end insert_num;
6/
Procedure created.
ID FIRST_NAME
101 Nithya
102 Maya
103 SCOTT
FUNCTION TO FIND FACTORIAL
2 return number is
3 i number(10);
4 f number:=1;
5 begin
7 f:=f*i;
8 end loop;
9 return f;
10 end;
11 /
Function created.
RESULT:
Aim:
To execute complex transactions and realize DCL & TCL commands on database.
DCL COMMANDS
The DCL language is used for controlling the access to the table and hence securing the
database. DCL is used to provide certain privileges to a particular user. Privileges are rights
to be allocated.The privilege commands are namely, Grant and Revoke.The various
privileges that can be granted or revoked are, Select Insert Delete Update References Execute
All.
GRANT COMMAND: It is used to create users and grant access to the database. It requires
database administrator (DBA) privilege, except that a user can change their password. A user
can grant access to their database objects to other users.
REVOKE COMMAND: Using this command , the DBA can revoke the granted database
privileges from the user.
TCL COMMAND
Queries:
Their schemas are as follows , Departments ( dept _no , dept_ name , dept_location );
Employees ( emp_id , emp_name , emp_salary );
Q1: Develop a query to grant all privileges of employees table into departments table
Ans: SQL> Grant all on employees to departments;
Grant succeeded.
Q2: Develop a query to grant some privileges of employees table into departments table
Ans: SQL> Grant select, update , insert on departments to departments with grant option;
Grant succeeded.
Q3: Develop a query to revoke all privileges of employees table from departments table
Ans: SQL> Revoke all on employees from departments; Revoke succeeded.
Q4: Develop a query to revoke some privileges of employees table from departments table
Ans: SQL> Revoke select, update , insert on departments from departments;
Revoke succeeded.
Q5: Write a query to implement the save point
Savepoint created.
1 Mathi AP 1 10000
1 Mathi AP 1 10000
5 Akalya AP 1 10000
1 Mathi AP 1 10000
Commit complete.
RESULT
Table created.
3 begin
4 :new.tot:=:new.m1+:new.m2+:new.m3;
5 :new.avrg:=:new.tot/3;
7 :new.result:='pass';
8 else
9 :new.result:='Fail';
10 end if;
11 end;
12 /
Trigger created.
1 row created.
Table
created.
SQL>
3 when(new.age>100)
4 begin
5 RAISE_APPLICATION_ERROR(-20998,'INVALID
ERROR');6* end;
SQL> /
Trigger created.
values('nithya',101,103)
*
ERROR at line 1:
ORA-20998: INVALID
ERROR ORA-06512: at
"SCOTT.T2", line 2
Aim:
To perform view & Index for database table.
VIEWS
Q1: The organization wants to display only the details of the employees those who are
ASP.
Solution:
job='ASP';View created.
A view contains rows and columns, just like a real table. The fields in a view
are fields from one or morereal tables in the database.
You can add SQL functions, WHERE, and JOIN statements to a view and present
the data as if the datawere coming from one single table.
Note: A view always shows up-to-date data! The database engine recreates the data,
using the view's SQLstatement, every time a user queries a view.
If you have the Northwind database you can see that it has several views installed by
default.
The view "Current Product List" lists all active products (products that are
not discontinued) from the"Products" table. The view is created with the
following SQL:
CREATE VIEW
[Current Product
List] ASSELECT
ProductID,
ProductName
FROM Products
WHERE Discontinued = No;
Then, we can
as follows:
SELECT *
FROM [Current
Product List];
Another view in the Northwind sample database selects every product in the
"Products" table with a unitprice higher than the average unit price:
Another view in the Northwind database calculates the total sale for each category
in 1997. Note that thisview selects its data from another view called "Product Sales
for 1997":
We can also add a condition to the query. Let's see the total sale only for
SQL CREATE OR
REPLACE VIEW
Syntax CREATE OR
REPLACE VIEW
view_name AS
SELECT column1,column2,...FROM table_name WHERE condition;
Now we want to add the "Category" column to the "Current Product List" view.
We will update the viewwith the following SQL:
If you want to create an index on a combination of columns, you can list the
column names within theparentheses, separated by commas:
MS Access:
SQL Server:
MySQL:
DEPTNO SAL
Q2: The organization wants to display only the details like empno, empname,
deptno,deptname of the employees. (Vertical portioning)
TABTYPE CLUSTERID
DEPT
TABLE EMP
TABLE
EMPVIEW
VIEW
EMPVIEW1
VIEW
empview1;View dropped.
Result:
Result:
Thus, the simple xml document creation has been executed successfully.
XML SCHEMA CREATION
Aim:
To create a program for XML Schema creation and display element and attributes.
Procedure:
Step-1: Open the XMLwriter.
Step-2: Click File->New->XML Document and name the Filename.
Step-3:Type the following program:
Source Code:
Filename:“Sche.xml”
<?xml version="1.0" encoding="UTF-8" ?>
<shiporder orderid="889923"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="sche.xsd">
<orderperson>John Smith</orderperson>
<shipto>
<name>Karthick</name>
<address>Langgt 23</address>
<city>4000 Stavanger</city>
<country>Norway</country>
</shipto>
<item>
<title>Empire Burlesque</title>
<note>Special Edition</note>
<quantity>1</quantity>
<price>10.90</price>
</item>
<item>
<title>Hide your heart</title>
<quantity>5</quantity>
<price>9.90</price>
</item>
</shiporder>
Step-4: Click File->New->XML Schema File and name the Filename.
Step-5: Type the following code:
Source Code:
Filename:“sche.xsd”
<?xml version="1.0" encoding="UTF-8" ?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="shiporder">
<xs:complexType>
<xs:sequence>
<xs:element name="orderperson" type="xs:string" />
<xs:element name="shipto">
<xs:complexType>
<xs:sequence>
<xs:element name="name" type="xs:string" />
<xs:element name="address" type="xs:string" />
<xs:element name="city" type="xs:string" />
<xs:element name="country" type="xs:string" />
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:element name="item" maxOccurs="unbounded">
<xs:complexType>
<xs:sequence>
<xs:element name="title" type="xs:string" />
<xs:element name="note" type="xs:string" minOccurs="0" />
<xs:element name="quantity" type="xs:positiveInteger" />
<xs:element name="price" type="xs:decimal" />
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:sequence>
<xs:attribute name="orderid" type="xs:string" use="required" />
</xs:complexType>
</xs:element>
</xs:schema>
Step-6: Finally validate the xml file by pressing the F7 key.
Output:
Result:
Thus, the program for XML Schema creation and display element and attributes has been
executed successfully.
Ex.No:11 NOSQL database tools
Aim:
To create document ,column & graph based data
➜ docker --version
Docker version 20.10.3, build 48d30b5
Awesome, now let’s proceed further and pull the mongo official image from dockerhub.
➜ docker images
REPOSITORY TAG IMAGE ID CREATED SIZE
mongo latest 81a352f64d83 16 hours ago 449MB
Now let’s start the docker container
MongoDB commands
MongoDB has a vibrant command-line interface, using which we can easily interact with
MongoDB.This tutorial will see some of the most widely used MongoDB commands.
root@659e36f1f2b9:/# mongo
MongoDB shell version v4.4.6
connecting to:
mongodb://127.0.0.1:27017/?compressors=disabled&gssapiServiceName=mongodb
................<supressed o/p>............
................<supressed o/p>............
---
>
List Databases
show dbs command will list all the databases present in MongoDB.By default, MongoDB has
some system databases created.
with the help of the db command; we can verify the current database user are in.
> db
naivetech
> db.createCollection('test')
{ "ok" : 1 }
To list all the collections in the mongo naivetech database, type the below command:
Drop a collection
> db.test.drop()
true
Delete a database
To drop any database, switch to that database and type the below command to delete:
> db.dropDatabase()
{ "dropped" : "naivetech", "ok" : 1 }
Now let’s proceed further and create another database, naivetechblog, and a new collection
of tech
> db.tech.insert({
... 'Kind': 'Mobile',
... 'lang': 'iphone 6s',
... 'Rating': 4.2
... })
WriteResult({ "nInserted" : 1 })
>
> db.tech.find()
{ "_id" : ObjectId("60c37656a9c3d411ad96c6e6"), "Kind" : "Mobile", "lang" : "iphone 6s",
"Rating" : 4.2 }
Pretty command
With MongoDB pretty command, we can print the output in a pretty format
> db.tech.find().pretty()
{
"_id" : ObjectId("60c37656a9c3d411ad96c6e6"),
"Kind" : "Mobile",
"lang" : "iphone 6s",
"Rating" : 4.2
}
>
Sometimes we need to insert more than 1 document at one go in our MongoDB collection.
With MongoDB insert many command, we can insert multiple documents.
> db.tech.insertMany([
... {
... 'Kind': 'Mobile',
... 'lang': 'iphone 6s',
... 'Rating': 4.2
... },
... {
... 'Kind': 'laptop',
... 'lang': 'acer',
... 'Rating': 3.9
... },
... {
... 'Kind': 'mobile',
... 'lang': 'samsung',
... 'Rating': 4.0
... },
... ])
{
"acknowledged" : true,
"insertedIds" : [
ObjectId("60c37883a9c3d411ad96c6e7"),
ObjectId("60c37883a9c3d411ad96c6e8"),
ObjectId("60c37883a9c3d411ad96c6e9")
]
}
Now let’s verify if all documents get created.
> db.tech.find()
{ "_id" : ObjectId("60c37656a9c3d411ad96c6e6"), "Kind" : "Mobile", "lang" : "iphone 6s",
"Rating" : 4.2 }
{ "_id" : ObjectId("60c37883a9c3d411ad96c6e7"), "Kind" : "Mobile", "lang" : "iphone 6s",
"Rating" : 4.2 }
{ "_id" : ObjectId("60c37883a9c3d411ad96c6e8"), "Kind" : "laptop", "lang" : "acer",
"Rating" : 3.9 }
{ "_id" : ObjectId("60c37883a9c3d411ad96c6e9"), "Kind" : "mobile", "lang" : "samsung",
"Rating" : 4 }
>
Search MongoDB
With the help of the find command, we can filter out/search the documents. Let’s try to find
the documents which contain mobile details.
> db.tech.find({Kind:'Mobile'})
{ "_id" : ObjectId("60c37656a9c3d411ad96c6e6"), "Kind" : "Mobile", "lang" : "iphone 6s",
"Rating" : 4.2 }
{ "_id" : ObjectId("60c37883a9c3d411ad96c6e7"), "Kind" : "Mobile", "lang" : "iphone 6s",
"Rating" : 4.2 }
>
findOne command displays the first output based on the filter criteria
db.tech.findOne({Kind:'Mobile'})
{
"_id" : ObjectId("60c37656a9c3d411ad96c6e6"),
"Kind" : "Mobile",
"lang" : "iphone 6s",
"Rating" : 4.2
}
>
Limit command
With the limit command, we can limit the no of documents to be displayed in MongoDB
> db.tech.find().limit(2)
{ "_id" : ObjectId("60c37656a9c3d411ad96c6e6"), "Kind" : "Mobile", "lang" : "iphone 6s",
"Rating" : 4.2 }
{ "_id" : ObjectId("60c37883a9c3d411ad96c6e7"), "Kind" : "Mobile", "lang" : "iphone 6s",
"Rating" : 4.2 }
>
Count command
Count command Counts the number of rows in the query output. Let’s try to find all
documents present in the MongoDB tech database.
> db.tech.find().count()
4
In MongoDB, we can insert data with different schema; we don’t have to stick to any schema
while inserting data in mongo collection.
Let’s insert a document in mongo with a different schema than we inserted earlier.
db.tech.insert({
'Kind': 'Mobile',
'lang': 'iphone 6s',
'Build_year': 2013 ,
'Rating': 4.2
})
Let’s verify if the data gets inserted.
db.tech.find()
{ "_id" : ObjectId("60c37656a9c3d411ad96c6e6"), "Kind" : "Mobile", "lang" : "iphone 6s",
"Rating" : 4.2 }
{ "_id" : ObjectId("60c37883a9c3d411ad96c6e7"), "Kind" : "Mobile", "lang" : "iphone 6s",
"Rating" : 4.2 }
{ "_id" : ObjectId("60c37883a9c3d411ad96c6e8"), "Kind" : "laptop", "lang" : "acer",
"Rating" : 3.9 }
{ "_id" : ObjectId("60c37883a9c3d411ad96c6e9"), "Kind" : "mobile", "lang" : "samsung",
"Rating" : 4 }
{ "_id" : ObjectId("60c38f5ca9c3d411ad96c6ea"), "Kind" : "Mobile", "lang" : "iphone 6s",
"Build_year" : 2013, "Rating" : 4.2 }
This session will see some of the most widely used update commands.
Update a row
> db.tech.find({Kind:'laptop'})
{ "_id" : ObjectId("60c37883a9c3d411ad96c6e8"), "Kind" : "laptop", "lang" : "acer",
"Rating" : 3.9
and run the update command
> db.tech.find({Kind:'laptop'})
{ "_id" : ObjectId("60c37883a9c3d411ad96c6e8"), "Kind" : "laptop", "Brand" : "samsung",
"Rating" : 4.3 }
upsert flag in the update command inserted a new document in MongoDB if the document
does not exist.
> db.tech.find()
{ "_id" : ObjectId("60c37656a9c3d411ad96c6e6"), "Kind" : "Mobile", "lang" : "iphone 6s",
"Rating" : 4.2 }
{ "_id" : ObjectId("60c37883a9c3d411ad96c6e7"), "Kind" : "Mobile", "lang" : "iphone 6s",
"Rating" : 4.2 }
{ "_id" : ObjectId("60c37883a9c3d411ad96c6e8"), "Kind" : "laptop", "Brand" : "vivo",
"Rating" : 4.3 }
{ "_id" : ObjectId("60c37883a9c3d411ad96c6e9"), "Kind" : "mobile", "lang" : "samsung",
"Rating" : 4 }
{ "_id" : ObjectId("60c38f5ca9c3d411ad96c6ea"), "Kind" : "Mobile", "lang" : "iphone 6s",
"Build_year" : 2013, "Rating" : 4.2 }
{ "_id" : ObjectId("60c3984464d905a23322abb1"), "Kind" : "game", "Brand" : "sony",
"Rating" : 4.3 }
Inc command
With the inc command, we can update the documents filed by specific value. Let’s run this
command and update the build_year by 2.
db.tech.find({Kind:'Mobile'})
{ "_id" : ObjectId("60c37656a9c3d411ad96c6e6"), "Kind" : "Mobile", "lang" : "iphone 6s",
"Rating" : 4.2 }
{ "_id" : ObjectId("60c37883a9c3d411ad96c6e7"), "Kind" : "Mobile", "lang" : "iphone 6s",
"Rating" : 4.2 }
{ "_id" : ObjectId("60c38f5ca9c3d411ad96c6ea"), "Kind" : "Mobile", "lang" : "iphone 6s",
"Build_year" : 2013, "Rating" : 4.2 }
Now, let’s update the document
db.tech.find({Kind:'Mobile'})
{ "_id" : ObjectId("60c37656a9c3d411ad96c6e6"), "Kind" : "Mobile", "lang" : "iphone 6s",
"Rating" : 4.2 }
{ "_id" : ObjectId("60c37883a9c3d411ad96c6e7"), "Kind" : "Mobile", "lang" : "iphone 6s",
"Rating" : 4.2 }
{ "_id" : ObjectId("60c38f5ca9c3d411ad96c6ea"), "Kind" : "Mobile", "lang" : "iphone 6s",
"Build_year" : 2015, "Rating" : 4.2 }
Rename command
With rename command, we can update the document filed in the MongoDB collection
db.tech.update({'Build_year': 2015},
{$rename:{
lang: "brand"
}})
verify the data after renamed
We can delete any document from the mongo collection with the delete command. Let’s
delete the Kind: game from the tech collection
db.tech.find()
{ "_id" : ObjectId("60c37656a9c3d411ad96c6e6"), "Kind" : "Mobile", "lang" : "iphone 6s",
"Rating" : 4.2 }
{ "_id" : ObjectId("60c37883a9c3d411ad96c6e7"), "Kind" : "Mobile", "lang" : "iphone 6s",
"Rating" : 4.2 }
{ "_id" : ObjectId("60c37883a9c3d411ad96c6e8"), "Kind" : "laptop", "Brand" : "vivo",
"Rating" : 4.3 }
{ "_id" : ObjectId("60c37883a9c3d411ad96c6e9"), "Kind" : "mobile", "lang" : "samsung",
"Rating" : 4 }
{ "_id" : ObjectId("60c38f5ca9c3d411ad96c6ea"), "Kind" : "Mobile", "Build_year" : 2015,
"Rating" : 4.2, "brand" : "iphone 6s" }
{ "_id" : ObjectId("60c3984464d905a23322abb1"), "Kind" : "game", "Brand" : "sony",
"Rating" : 4.3 }
Delete the document
db.tech.remove({"Kind":"game"})
WriteResult({ "nRemoved" : 1 })
Verify the data after the deletion
db.tech.find()
{ "_id" : ObjectId("60c37656a9c3d411ad96c6e6"), "Kind" : "Mobile", "lang" : "iphone 6s",
"Rating" : 4.2 }
{ "_id" : ObjectId("60c37883a9c3d411ad96c6e7"), "Kind" : "Mobile", "lang" : "iphone 6s",
"Rating" : 4.2 }
{ "_id" : ObjectId("60c37883a9c3d411ad96c6e8"), "Kind" : "laptop", "Brand" : "vivo",
"Rating" : 4.3 }
{ "_id" : ObjectId("60c37883a9c3d411ad96c6e9"), "Kind" : "mobile", "lang" : "samsung",
"Rating" : 4 }
{ "_id" : ObjectId("60c38f5ca9c3d411ad96c6ea"), "Kind" : "Mobile", "Build_year" : 2015,
"Rating" : 4.2, "brand" : "iphone 6s" }
In MongoDB, we can use less than one command to filter out the document based on filter
criteria. Let’s filter out the Mobile whose rating is less than 4.2
Let’s filter out the Mobile whose rating is greater than 4.2
Similar to the greater than command, we can use the greater than equal command in
MongoDB to filter out documents.
Result:
Aim:
import javax.swing.*;
import java.awt.*;
import java.awt.Image;
import java.awt.event.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.print.*;
import javafx.print.Printer;
import java.io.*;
import java.io.IOException;
area2.setText(area2.getText()
+ "Student Name: "
+ tf1.getText()
+ "\n");
area2.setText(area2.getText()
+ "Father's Name: "
+ tf2.getText()
+ "\n");
area2.setText(area2.getText()
+ "RollNumber: "
+ tf3.getText()
+ "\n");
area2.setText(area2.getText()
+ "Email ID: "
+ tf4.getText()
+ "\n");
area2.setText(area2.getText()
+ "Contact Number: "
+ tf5.getText()
+ "\n");
area2.setText(area2.getText()
+ "Wants to take: "
+ cb.getSelectedItem()
.toString()
+ "\n");
if (rb1.isSelected()) {
area2.setText(area2.getText()
+ "Wants to Join in "
+ "School of Engineering "
+ "and Applied Sciences\n");
}
if (rb2.isSelected()) {
area2.setText(area2.getText()
+ "Wants to Join in "
+ "School of Liberal "
+ "Arts and Sciences\n");
}
if (rb3.isSelected()) {
area2.setText(area2.getText()
+ "Wants to be a "
+ "Hosteller \n");
}
if (rb4.isSelected()) {
area2.setText(area2.getText()
+ "Wants to be a "
+ "Day Scholar \n");
}
area2.setText(area2.getText()
+ "Had chosen: "
+ list1.getSelectedValue()
.toString()
+ "\n");
area2.setText(area2.getText()
+ "Had chosen: "
+ list2.getSelectedValue()
.toString()
+ "\n");
if (index2 == 1) {
area2.setText(area2.getText()
+" "
+ "Total amount to be paid "
+ "is 3.9 Lakhs \n");
}
if (index2 == 2) {
area2.setText(area2.getText()
+" "
+ "Total amount to be paid "
+ "is 3.8 Lakhs \n");
}
if (index2 == 3) {
area2.setText(area2.getText()
+" "
+ "Total amount to be paid "
+ "is 3.7 Lakhs \n");
}
if (index2 == 4) {
area2.setText(area2.getText()
+" "
+ "Total amount to be paid "
+ "is 2.9 Lakhs \n");
}
if (e.getSource() == Receipt) {
try {
FileWriter fw
= new FileWriter(
"java.txt", true);
fw.write(area2.getText());
fw.close();
}
catch (Exception ae) {
System.out.println(ae);
}
}
JOptionPane.showMessageDialog(
area2, "DATA SAVED SUCCESSFULLY");
};
});
addWindowListener(
new WindowAdapter() {
public void windowClosing(
WindowEvent we)
{
System.exit(0);
}
});
setSize(800, 800);
setLayout(null);
setVisible(true);
setBackground(Color.cyan);
}
public static void main(String[] args)
{
new fee();
}
}
Output:
•
• When all the details are added in the respective fields:
•
• When the receipt button is pressed:
•
• When the data is stored in a text file:
•
• When print button is clicked, the following options are shown. If the printer is
available, then it can be directly printed.
•
• Preview of the document if the printer is available:
Result:
Thus a simple GUI based database application developed & executed.
Ex.No:13 Case Study
AIM:
All major repairs and maintenance are done by subcontractors (i.e. franchised
garages), with whom CRC has long-term agreements. Therefore the data about
garages to be kept in the database includes garage names, addresses, range of
services and the like. Some garages require payments immediately after a repair has
been made; with others CRC has made arrangements for credit facilities. Company
expenditures are to be registered for all outgoings connected with purchases, repairs,
maintenance, insurance etc.
Similarly the cash inflow coming from all sources - car hire, car sales,
insurance claims - must be kept of file.CRC maintains a reasonably stable client
base. For this privileged category of customers special credit card facilities are
provided. These customers may also book in advance a particular car. These
reservations can be made for any period of time up to one month. Casual customers
must pay a deposit for an estimated time of rental, unless they wish to pay by credit
card. All major credit cards are accepted. Personal details (such as name, address,
telephone number, driving license, number) about each customer are kept in the
database.
Result:
Thus different case studies are performed.
Content Beyond the Syllabus
Aim:
To study about various database tools
The SolarWinds Database Performance Analyzer is a live monitoring tool for databases and
it runs on-premises. The system includes an alerting mechanism that draws the DBA’s attention
to performance issues, such as resource locks or long-running queries. Watching the usage of
the database enables the monitor to identify the reasons why some queries run too long.
The database performance monitoring part of the tool is very similar to the typical behavior
of a network performance monitor. A network performance monitor tracks a list of attributes
and sets thresholds of acceptable status levels. The Database Performance Analyzer applies
this strategy to databases.
The benefit of threshold-based monitoring is that the DBA doesn’t have to sit watching the
live performance graphs on the screen. Instead, admin staff can assume that everything is OK
with the database until otherwise notified. If a status passes a threshold, the Database
Performance Monitor raises an alert. That should draw the attention of technical staff back to
the tool in order to find out what performance limits are being approached, what caused the
problem, and how to head off disaster.
Threshold levels are placed well within the database’s capabilities, so this is not a last-minute
warning. The alerts give the DBA enough time to adjust resources and keep the database
running smoothly. SolarWinds deployed machine learning techniques inside the coding of
the Database Performance Analyzer so the tool adjusts thresholds over time, as it processes
more live performance tracking data. This means that the tool will customize itself to the
specific needs of the organization rather than being a standard tool applied in all
implementations.
The query analysis section of the Database Analyzer will produce recommendations on more
efficient query structures. It can also work out how indexes, views, and other database objects
can be adjusted to improve query response times. This section of the Database Performance
Analyzer also deploys machine learning.
The Database Performance Analyzer is primarily a DBA tool. The greatest value that the tool
provides comes from its alerting system because that enables DBAs to pay attention to other
tasks while the software watches normal activity. The query optimizer tool is also a useful
system to identify code that needs to be reworked, although it probably wouldn’t be suitable
for developers to have direct access to the analyzer – they would only need to see the output of
an analysis of a query. The software runs on Windows Server and Linux.
Pros:
• Highly intuitive DB management system tailored for medium to large size database
implementations
• Monitors in real-time, offering a number of alert and notification options that can
integrate into popular helpdesk solutions
• Threshold monitoring helps keep teams proactive, and fix issues before they impact
performance
• Dashboards are highly customizable, and be tailored to individuals or teams
• Built-in query analysis helps DBAs build more efficient queries
• Leverages machines learning to identify performance bottlenecks
Cons:
Datadog Database Monitoring provides monitoring services for all of the services and
applications that support your user-facing software and that includes databases. This package
is able to link together the interdependencies between services, creating a stack view that
reaches all the way down to the server resources that underpin them.
• Dependency mapping
Datadog Database Monitoring is a similar service to the SolarWinds tool except that it is a
SaaS package. The Datadog system includes simultaneous automated monitoring for multiple
database instances, which can all be of different DBMSs. This provides alerts if performance
is impaired. The tool also examines database instance interaction with server resources and
identifies the root cause of performance issues.
The combination of monitors for all types of infrastructure means that Datadog is able to show
you database performance in context. Your database is dependent on other systems and
performance problems might not be caused by their internal processes but by underlying
resource shortages or access locks.
The highest plan of Datadog Database Monitoring includes a machine learning process that
is able to work out what services access which resources and spot when demand is likely to use
up full capacity. With this dependency resource requirement, you can head off performance
problems before they get bad enough to be noticed by users.
After quickly ruling out external factors as the cause of database performance problems,
Datadog also provides database query and database structure optimization tools. Adding or
removing indexes could be the answer to your problems and Datadog’s database
analysis system quickly shows you how.
While examining the activities of the database to fulfill the demands of specific requests, you
can simultaneously look beneath the DBMS to identify which server resources each query
impacts.
Once you are confident that the database is finely tuned, you can leave Datadog to perform
ongoing monitoring unattended. A system of thresholds within the monitor will notify you if
a performance statistic is bringing in numbers that exceed your requirements for satisfactory
operations. Alerts can be forwarded as notifications by email or through apps such
as PagerDuty, Jira, Slack, and Webhooks.
Datadog Database Monitoring includes database and query optimization systems as well as
monitoring services. This cloud-based platform will give you an overview of all of your
databases and then let you examine the performance of each database. The system watches all
infrastructure that relates to your databases, making root cause analysis quicker when things
go wrong. The Infrastructure system includes an alerting mechanism that lets you leave the
package to watch over your databases unattended.
Like the SolarWinds tool, this system is for use by DBAs. The query analyzer utility in Datadog
is not as detailed as that available in the SolarWinds system. It will identify queries that perform
badly but won’t provide detailed explanations as to why. So, this tool isn’t for use by code
developers.
Pros:
• System-wide database performance overviews
Cons:
• The free trial period is only two weeks
• Database visualization
• Query builder
Aquafold Aqua Data Studio is a completely different tool to the two preceding systems. This
package is intended for use by developers. It does have a database instance import system that
also enables ERDs to be adjusted and then applied to the instance in the form of object creation
and alteration scripts. However, these are secondary functions to the main aim of the tool,
which is to support the creation of efficient queries.
Aqua Data Studio can be used to develop and analyze databases on-premises and on the cloud.
The system offers an SSH Terminal to facilitate access to remote servers to access the
database management system and access database objects.
The DBMSs that Aqua Data Studio can interact with are Oracle, DB2 LUW, DB2 z/OS,
MariaDB, Microsoft SQL Server, MySQL, PostGreSQL, Redshift, Greenplum, ParAccel,
Teradata Aster, Netezza, Hive, Spark, Impala, and Sybase.
You can use the system to administer databases as well as create them. Ongoing performance
analysis lets DBAs check on the response times of databases and adjust resources accordingly.
The development tools in the package include an interactive query builder that helps those
with little knowledge of SQL create data access queries to feed into their new applications. The
service also supports SQL to insert, update, and delete records, keeping an eye on the
performance of indexes.
This system should be used by developers and development project managers. It isn’t meant
for ongoing performance monitoring or management of databases by DBAs. You would get
the best use out of this tool if a new requirement necessitates the creation of new objects as
well as new applications, so you would end up creating new database structures simultaneously
with the construction of queries to input and extract data. This is an on-premises software
package for Windows, Linux, and macOS.
Pros:
• Links together query performance with database structures
Cons:
• A SaaS version would be nice to have
RazorSQL
RazorSQL is an extensive suite of SQL management tools that will help you run a relational
database that is accessed with SQL. The suite is able to communicate with a long list of
RDBMSs, including Oracle, MySQL, SQL Server, PostgreSQL, Informix, and Ingres.
Key Features:
• Unifies management access to multiple DBMSs
• Standardized SQL
• Query interpreter
• SQL editor
RazorSQL acts as a GUI frontend for any database instance. It provides a view of all of the
objects in an instance and provides administration functions that enable objects to be added or
altered and it will also assist with migrating or replicating an instance structure. Other admin
tools include a bulk data loader. Developers can use this tool to refer to tables and indexes and
use an editor to build SQL-based programs and scripts.
The interoperability of the tool is particularly useful if you have to deal with several database
types on your site. The SQL command set is not exactly the same for all RDBMSs, so you can
waste time entering the wrong command format when you switch from one system to another.
RazorSQL presents a GUI interface, which it then interprets into commands that get executed
in the database. However, if you want to write your own scripts, the utility includes an SQL
Editor, which will highlight syntax errors.
The package includes just about all of the functions that you will need in order to administer a
database., including backing up data in tables. One thing that is missing from this suite is a
form builder that would enable you to create front ends to give your user community safe and
easy access to the database.
RazorSQL can be used with more than 40 DBMSs and its program editor is able to support
more than 20 programming languages. This is an excellent tool for DBAs and developers.
Ideally, the tool would be used to make minor adjustments to an instance rather than as a system
to build a brand-new database.
Pros:
• Designed specifically for DevOps and DBAs
• Offers syntax highlighting and code completion to help speed up larger projects
• Supports Windows, Linux, and Mac, making it more flexible than some of its
competitors
Cons:
• Interface could use improvement, default layout can get cluttered very quickly
This is a paid tool but is very reasonably priced. You can buy the standard package which
includes a year of updates and support or opt for more expensive packages with longer support
periods. Another dimension in the pricing structure of RazorSQL is the number of people who
will use it.
Result:
Thus various database tools are studied.