Sei sulla pagina 1di 121

Database Management Systems Lab T.

E (Computer Engineering)

SINHGAD TECHNICAL EDUCATION SOCIETY’S


RMD SINHGAD SCHOOL OF ENGINEERING
Warje, Pune 411058

Department of Computer Engineering

T.E. Computer (Sem-I)

Lab Manual
Database Management System Laboratory

Teaching Scheme Examination Scheme


Practical: 4 Hrs/Week University Practical: 50 Marks
University Term work: 25 Marks

Prepared By:

Ms. Gauri S. Patil


(Assistant Professor, Computer Engineering Department)

Ms. Jaitee A. Bankar


(Assistant Professor, Computer Engineering Department)

Department of Computer Engineering 1


Database Management Systems Lab T.E (Computer Engineering)

SINHGAD TECHNICAL EDUCATION SOCIETY’S


RMD SINHGAD SCHOOL OF ENGINEERING
Warje, Pune 411058

Department of Computer Engineering

Vision

उउउउउउउउउउउउउ उउउउउउउउउउउउउउ उउउउउउउउउ उउउउउउउउउ


उउउउउ

We are committed to produce good human beings along with good engineers

Mission

Holistic development of students and teachers is what we believe in and work for. We strive to
achieve this by imbibing a unique value system, transparent work culture, excellent academic
and physical environment conductive to learning, creativity and technology transfer. Our
mandate is to generate, preserve and share knowledge for developing a vibrant society

Department of Computer Engineering 2


Database Management Systems Lab T.E (Computer Engineering)

LABORATORY MANUAL CONTENTS

This manual is intended for the Third year students of Computer Science and Engineering in the
subject of Database Management System. This manual typically contains practical/Lab Sessions
related Database Management System covering various aspects related the subject to enhanced
understanding.

Students are advised to thoroughly go through this manual rather than only topics
mentioned in the syllabus as practical aspects are the key to understanding and conceptual
visualization of theoretical aspects covered in the books.

Good Luck

Prof. Vina M. Lomte Prof. Gauri S. Patil


Head of Computer Engineering Prof. Jaitee Bankar
Assistant Professor

Department of Computer Engineering 3


Database Management Systems Lab T.E (Computer Engineering)

GUIDELINES FOR STUDENTS

1. Students should be regular and come prepared for the lab practice.
2. In case a student misses a class, it is his/her responsibility to complete that missed
experiment(s).
3. Students should bring the observation book, lab journal and lab manual. Prescribed
textbook and class notes can be kept ready for reference if required.
4. They should implement the given Program individually.
5. While conducting the experiments students should see that their programs would meet the
following criteria:
 Programs should be interactive with appropriate prompt messages, error messages if
any,and descriptive messages for outputs.
 Programs should perform input validation (Data type, range error, etc.) and give
appropriate error messages and suggest corrective actions.
 Comments should be used to give the statement of the problem and every function should
indicate the purpose of the function, inputs and outputs.
 Statements within the program should be properly indented
 Use meaningful names for variables and functions.
 Make use of Constants and type definitions wherever needed.
6. Once the experiment(s) get executed, they should show the program and results to the
instructors and copy the same in their observation book.
7. Questions for lab tests and exam need not necessarily be limited to the questions in the
manual, but could involve some variations and / or combinations of the questions

Department of Computer Engineering 4


Database Management Systems Lab T.E (Computer Engineering)

COURSE OBJECTIVES

• To develop basic, intermediate and advanced Database programming skills


• To develop basic Database administration skills
• To percept transaction processing

COURSE OUTCOME

On completion of the course, student will be able to:

 Develop the ability to handle databases of varying complexities


 Use advanced database Programming concepts

Department of Computer Engineering 5


Database Management Systems Lab T.E (Computer Engineering)

List of Laboratory Assignments

Sr. No. Assignment Name


Group-A: Database Programming Languages – SQL, PL/SQL
1 Study of Open Source Relational Databases : MySQL
Design and Develop SQL DDL statements which demonstrate the use of SQL objects such as Table,
2
View, Index, Sequence, Synonym
Design at least 10 SQL queries for suitable database application using SQL DML statements: Insert,
3
Select, Update, Delete with operators, functions, and set operator
Design at least 10 SQL queries for suitable database application using SQL DML statements: all types
4
of Join, Sub-Query and View
Unnamed PL/SQL code block: Use of Control structure and Exception handling is mandatory. Write a
PL/SQL block of code for the following requirements:- Schema:
1. Borrower(Rollin, Name, DateofIssue, NameofBook, Status)
2. Fine(Roll_no,Date,Amt)
 Accept roll_no& name of book from user.
5  Check the number of days (from date of issue), if days are between 15 to 30 then fine amount
will be Rs 5per day.
 If no. of days>30, per day fine will be Rs 50 per day & for days less than 30, Rs. 5 per day.
 After submitting the book, status will change from I to R.
 If condition of fine is true, then details will be stored into fine table.
Frame the problem statement for writing PL/SQL block in line with above statement.
Cursors: (All types: Implicit, Explicit, Cursor FOR Loop, Parameterized Cursor)
Write a PL/SQL block of code using parameterized Cursor, that will merge the data available in the
newly created table N_RollCall with the data available in the table O_RollCall. If the data in the first
6 table already exist in the second table then that data should be skipped.
Frame the separate problem statement for writing PL/SQL block to implement all types of
Cursors in line with above statement. The problem statement should clearly state the
requirements.
PL/SQL Stored Procedure and Stored Function.
Write a Stored Procedure namely proc_Grade for the categorization of student. If marks scored by
students in examination is <=1500 and marks>=990 then student will be placed in distinction category
if marks scored are between 989 and900 category is first class, if marks 899 and 825 category is Higher
7 Second Class
Write a PL/SQL block for using procedure created with above requirement. Stud_Marks(name,
total_marks) Result(Roll,Name, Class)
Frame the separate problem statement for writing PL/SQL Stored Procedure and function, in
line with above statement. The problem statement should clearly state the requirements.
Database Trigger (All Types: Row level and Statement level triggers, Before and After Triggers). Write
a database trigger on Library table. The System should keep track of the records that are being updated
8 or deleted. The old value of updated or deleted records should be added in Library_Audit table.
Frame the problem statement for writing Database Triggers of all types, in-line with above
statement. The problem statement should clearly state the requirements.
Group-B: Large Scale Databases

Department of Computer Engineering 6


Database Management Systems Lab T.E (Computer Engineering)

1 Study of Open Source NOSQL Database: MongoDB (Installation, Basic CRUD operations, Execution)

Design and Develop MongoDB Queries using CRUD operations. (Use CRUD operations, SAVE
2
method, logical operators)

3 Implement aggregation and indexing with suitable example using MongoDB

4 Implement Map reduces operation with suitable example using MongoDB


5 Design and Implement any 5 query using MongoDB
6 Create simple objects and array objects using JSON
7 Encode and Decode JSON Objects using Java/Perl/PHP/Python/Ruby
Group-C: Mini Project : Database Project Life Cycle
Write a program to implement MogoDB database connectivity with PHP/ python/Java Implement
1
Database navigation operations (add, delete, edit etc. ) using ODBC/JDBC
Implement MYSQL/Oracle database connectivity with PHP/ python/Java Implement Database
2
navigation operations (add, delete, edit,) using ODBC/JDBC
Using the database concepts covered in Part-I & Part-II & connectivity concepts covered in Part C,
students in group are expected to design and develop database application with following details:
Requirement Gathering and Scope finalization
Database Analysis and Design:
 Design Entity Relationship Model, Relational Model, Database Normalization
Implementation :
 Front End : Java/Perl/PHP/Python/Ruby/.net
3  Backend : MongoDB/MYSQL/Oracle
 Database Connectivity : ODBC/JDBC
Testing : Data Validation
Group of students should submit the Project Report which will be consist of documentation related to
different phases of Software Development Life Cycle: Title of the Project, Abstract, Introduction,
scope, Requirements, Data Modeling features, Data Dictionary, Relational Database Design, Database
Normalization, Graphical User Interface, Source Code, Testing document, Conclusion. Instructor
should maintain progress report of mini project throughout the semester from project group and assign
marks as a part of the term work

Department of Computer Engineering 7


Database Management Systems Lab T.E (Computer Engineering)

GROUP A

Department of Computer Engineering 8


Database Management Systems Lab T.E (Computer Engineering)

ASSIGNMENT NO: 1

Title: Study of Open Source Relational Databases: MySQL


Objectives: To learn and understand open source relational databases
Outcomes: Students will be able to learn concepts of relational databases
Hardware requirements: Any CPU with Pentium Processor or similar, 256 MB RAM or more, 1 GB
Hard Disk or more.
Software requirements: Ubuntu 14 Operating System, MySQL

Theory: A database-management system (DBMS) is a collection of interrelated data and a set of


programs to access those data. The collection of data, usually referred to as the database, contains
information relevant to an enterprise. The primary goal of a DBMS is to provide a way to store and
retrieve database information that is both convenient and efficient.

Database Applications:
 Banking: transactions
 Airlines: reservations, schedules
 Universities: registration, grades
 Sales: customers, products, purchases
 Online retailers: order tracking, customized recommendations
 Manufacturing: production, inventory, orders, supply chain
 Human resources: employee records, salaries, tax deductions

Data Models:
 Relational model
 Entity-Relationship data model (mainly for database design)
 Object-based data models (Object-oriented and Object-relational)
 Semi-structured data model (XML)
 Other older models:
 Network model
 Hierarchical model

Department of Computer Engineering 9


Database Management Systems Lab T.E (Computer Engineering)

A database is a means of storing information in such a way that information can be retrieved
from it. In simplest terms, a relational database is one that presents information in tables with rows and
columns. A table is referred to as a relation in the sense that it is a collection of objects of the same type
(rows). Data in a table can be related according to common keys or concepts, and the ability to retrieve
related data from a table is the basis for the term relational database. A Database Management System
(DBMS) handles the way data is stored, maintained, and retrieved. In the case of a relational database,
a Relational Database Management System (RDBMS) performs these tasks.
A relational database management system (RDBMS) is a program that lets you create,
update, and administer a relational database. Most commercial RDBMS’s use the Structured Query
Language (SQL) to access the database, although SQL was invented after the development of the
relational model and is not necessary for its use.
MySQL open source RDBMS overview: MySQL is a popular open source relational database
management system (RDBMS) choice for web-based applications. Developers, database administrators
and DevOps teams use MySQL to build and manage next-generation web- and cloud-based
applications. With most open source RDBMS options, MySQL is available in several different editions
and runs on Windows, OS X, Solaris, FreeBSD and other variants of Linux and Unix:
 MySQL Classic Edition, available to only independent software vendors, OEMs and value-
added resellers, is designed to be an Embeddable database for read-intensive applications.
 MySQL Community Edition Is the free downloadable version of MySQL available under the
GNU General Public License (GPL).
 MySQL Standard Edition Is the entry-level RDBMS offering for online transaction processing
 MySQL Enterprise Edition Adds advanced features, management tools (including OEM for
MySQL) and technical support.
 MySQL Cluster Carrier Grade Editionis designed for Web and cloud development.

Data types supported by MySQL open source RDBMS: MySQL data types include numeric types,
date and time types, string types (including binary, character and Binary Large Object), and spatial
types. Additionally, MySQL will map certain data types from other DBMS to MySQL data types for
easier portability.

Department of Computer Engineering 10


Database Management Systems Lab T.E (Computer Engineering)

Install MySQL on Ubuntu 14.04: MySQL is an open-source database management system,


commonly installed as part of the popular LAMP(Linux, Apache, MySQL, and PHP/Python/Perl)
stack. It uses a relational database and SQL (Structured Query Language) to manage its data. The short
version of the installation is simple: update your package index, install the mysql-server package, and
then run the included security and database initialization scripts.

Step 1 — Installing MySQL: There are two ways to install MySQL. You can either use one of the
versions included in the APT package repository by default (which are 5.5 and 5.6), or you can install
the latest version (currently 5.7) by manually adding MySQL’s repository first. You can just use the
mysql-server APT package, which just installs the latest version for your Linuxdistribution. To install
MySQL this way, update the package index on your server and install the package with apt-get.

 sudo apt-get update


 sudo apt-get install mysql-server

You’ll be prompted to create a root password during the installation. Choose a secure one and make
sure you remember it, because you’ll need it later. Move on to step two from here.

Installing MySQL 5.5 or 5.6


If you want to install MySQL 5.5 or 5.6 specifically, the process is still very straightforward. First,
update the package index on your server.
 sudo apt-get update
 Then, to install MySQL 5.5, install the mysql-server-5.5 package.
 sudo apt-get install mysql-server-5.5
 To install MySQL 5.6, install the mysql-server-5.6 package instead.
 sudo apt-get install mysql-server-5.6
For both options, you’ll be prompted to create a root password during the installation. Choose a secure
one and make sure you remember it, because you’ll need it later.

Step 2 — Configuring MySQL: First, you’ll want to run the included security script. This changes
some of the less secure default options for things like remote root logins and sample users.
 sudomysql_secure_installation

Department of Computer Engineering 11


Database Management Systems Lab T.E (Computer Engineering)

 This will prompt you for the root password you created in step one. You can press ENTER to
accept the defaults for all the subsequent questions, with the exception of the one that asks if
you’d like to change the root password. You just set it in step one, so you don’t have to change
it now.
 Next, we’ll initialize the MySQL data directory, which is where MySQL stores its data. How
you do this depends on which version of MySQL you’re running. You can check your version
of MySQL with the following command.
 mysql –version
If you’re using a version of MySQL earlier than 5.7.6, you should initialize the data directory by
running mysql_install_db.
 sudomysql_install_db

Step 3 — Testing MySQL: Regardless of how you installed it, MySQL should have started running
automatically. To test this, check its status.
 service mysql status

If MySQL isn’t running, you can start it with sudo service mysql start.
For an additional check, you can try connecting to the database using the mysqladmin tool, which is a
client that lets you run administrative commands. For example, this command says to connect to
MySQL as root (-u root), prompt for a password (-p), and return the version.
 mysqladmin -p -u root version

Step 4 — Log in MySQL: Use following command to log in to MySQL


In terminal, write
 sudomysql –u root –p
You will be prompted for password. After log in you can see mysql> prompt to execute queries

Conclusion: Studied concept of relational databases, MySQL DBMS and steps to install MySQL on
Ubuntu O.S.

Department of Computer Engineering 12


Database Management Systems Lab T.E (Computer Engineering)

ASSIGNMENT NO: 2

Title: Design and Develop SQL DDL statements which demonstrate the use of SQL objects such as
Tables, View, Sequence, Synonym
Objectives: To learn and SQL DDL statements which demonstrate the use of SQL objects such as
Table, View, Index, Sequence, Synonym
Outcomes: Students will be able to learn concepts of DDL commands.

Requirements:
Software Requirements: Maria DB, Fedora 20, MYSQL
Hardware Requirements: CPU: Intel Core or Xeon 3GHz (or Dual Core 2GHz) or equal AMD, Cores:
Single (Dual/Quad Core is recommended) , RAM: 4 GB (6 GBrecommended)

Theory:

1. Data Definition Language: DDL (Data Definition Language) statements are used to create, delete,
or change the objects of a database. Typically a database administrator is responsible for using DDL
statements or production databases in a large database system. It contains the commands used to create
and destroy databases and database objects. These commands will primarily be used by database
administrators during the setup and removal phases of a database project.

The commands used are:


 Create – It is used to create a table.
 Alter – This command is used to add a new column, modify the existing column definition and
to include or drop integrity constraint.
 Drop – It will delete the table structure provided the table SHOULD BE EMPTY.
 Truncate – If there is no further use of records stored in a table and the structure has to be
retained, and then the records alone can be deleted.
 Describe – This is used to view the structure of the table.

Table Creation:
Rules:
 Reserved words cannot be used.
 Underscore, numerals, letters are allowed but not blank space.
 Maximum length for the table name is 30 characters.
 2 different tables should not have same name.
 We should specify a unique column name.
 We should specify proper data type along with width.
 We can include “not null” condition when needed. By default it is ‘null’.

DDL Commands:
a) Create Table Command:
The CREATE TABLE statement is used to create a new table in a database.

Department of Computer Engineering 13


Database Management Systems Lab T.E (Computer Engineering)

Syntax:
CREATE TABLE <TABLE_NAME>
(
column_name1 datatype1(size),
column_name2 datatype2(size),
column_name3 datatype3(size),
column_name4 datatype4(size)
……
);

Example:
CREATE TABLE Student
( student_id INT,
name VARCHAR(100),
age INT);
The above example will create a new table with name Student in the current database with 3
columns, namely student_id, name and age, where the column student_id will only store
integer, name will hold upto 100 characters and age will again store only integer value.

Creating table from another (existing table) table:


Syntax-
CREATE TABLE new_table_name AS
SELECT [ column1, column2...columnN ]
FROM existing_table_name;

Example:
CREATE TABLE SALARY AS SELECT ID, SALARY FROM CUSTOMERS;
Above example creates a table SALARY using the CUSTOMERS table and having the fields
customer ID and customer SALARY.

b) Alter table Command:


The ALTER command is used to add, delete or modify columns in an existing table. The
ALTER command can also be to add and drop various constraints on an existing table.

Syntax:
The basic syntax of an ALTER TABLE command to add a “New Column” in an existing table
is as follows:
ALTER TABLE table_name ADD column_name datatype;

The basic syntax of an ALTER TABLE command to “Drop Column” in an existing table is as
follows:
ALTER TABLE table_name DROP COLUMN column_name;

The basic syntax of an ALTER TABLE command to change the “Data Type” of a column in a
table is as follows:
ALTER TABLE table_name MODIFY COLUMN column_name datatype;

Department of Computer Engineering 14


Database Management Systems Lab T.E (Computer Engineering)

The basic syntax of an ALTER TABLE command to add a “Not Null” constraint to a column in
a table is as follows:
ALTER TABLE table_name MODIFY column_name datatype NOT NULL;

The basic syntax of ALTER TABLE to “Add Unique Constraint” to a table is as follows:
ALTER TABLE table_name
ADD CONSTRAINT MyUniqueConstraint UNIQUE(column1, column2...);

The basic syntax of an ALTER TABLE command to “Add Check Constraint” to a table is as
follows:
ALTER TABLE table_name ADD CONSTRAINT MyUniqueConstraint CHECK
(CONDITION);

The basic syntax of an ALTER TABLE command to “Add Primary Key” constraint to a table is
as follows:
ALTER TABLE table_name ADD CONSTRAINT MyPrimaryKey PRIMARY KEY
(column1, column2...);

The basic syntax of an ALTER TABLE command to “Drop Constraint” from a table is as
follows:
ALTER TABLE table_name DROP INDEX MyUniqueConstraint;

The basic syntax of an ALTER TABLE command to “Drop Primary Key” constraint from a
table is as follows.
ALTER TABLE table_name DROP PRIMARY KEY;

Example 1:
Following is the example to ADD a New Column to an existing table named Customers:

ALTER TABLE Customers ADD Gender char(1);

Now, the CUSTOMERS table is changed and a new column name Gender will be added to the
Customers table.

Example 2:
Following is the example to DROP Gender column from the existing table.

ALTER TABLE Customers DROP Gender;

Now, the Customers table is changed and the Gender column will be dropped from the
Customers table.

c) Renaming a table:
To rename a table, use the RENAME option of the ALTER TABLE statement. The following
example renames table test_tbl to alt_test:

ALTER TABLE test_tbl RENAME TO alt_test;

Department of Computer Engineering 15


Database Management Systems Lab T.E (Computer Engineering)

d) Drop table command:


The MySQL DROP TABLE statement allows to remove or delete a table from the MySQL
database.

Syntax:
DROP TABLE table_name;

Example:
DROP TABLE personal_info;

The above example will permanently remove the personal_info table.

2. MySQL CREATE Views:-


A database view is a virtual table or logical table which is defined as a SQL SELECT
query with joins. Because a database view is similar to a database table, which consists of rows
and columns, so we can query data against it. Most database management systems, including
MySQL, allow to update data in the underlying tables through the database view with some
prerequisites. A database view is dynamic because it is not related to the physical schema. The
database system stores views as a SQL SELECT statement with joins. When the data of the
tables changes, the view reflects that changes as well.

Syntax:
CREATE [OR REPLACE] VIEW view_name AS
SELECT columns
FROM tables
[WHERE conditions];

The CREATE VIEW statement creates a new view, or replaces an existing view if
the OR REPLACE clause is given. If the view does not exist, CREATE OR REPLACE
VIEW is the same as CREATE VIEW. If the view does exist, CREATE OR REPLACE
VIEW replaces it.
The select_statement is a SELECT statement that provides the definition of the view.
The select_statement can select from base tables or other views.
The view definition is “frozen” at creation time and is not affected by subsequent changes to the
definitions of the underlying tables. For example, if a view is defined as SELECT * on a table,
new columns added to the table later do not become part of the view, and columns dropped
from the table will result in an error when selecting from the view.
A view belongs to a database. By default, a new view is created in the default database. To
create the view explicitly in a given database, use db_name.view_name syntax to qualify the
view name with the database name:
CREATE VIEW test.v AS SELECT * FROM t;

A view can be created from many kinds of SELECT statements. It can refer to base tables or
other views. It can use joins, UNION, and subqueries. The SELECT need not even refer to any
tables:
CREATE VIEW v_today (today) AS SELECT CURRENT_DATE;

Department of Computer Engineering 16


Database Management Systems Lab T.E (Computer Engineering)

The following example defines a view that selects two columns from another table as well as an
expression calculated from those columns:

mysql> CREATE TABLE t (qty INT, price INT);


mysql> INSERT INTO t VALUES(3, 50);
mysql> CREATE VIEW v AS SELECT qty, price, qty*price AS value FROM t;
mysql> SELECT * FROM v;
+------+-------+-------+
| qty | price | value |
+------+-------+-------+
| 3 | 50 | 150 |
+------+-------+-------+

3. MySQL CREATE INDEX:-


In MySQL, an index can be created on a table when the table is created with CREATE TABLE
command. Otherwise, CREATE INDEX enables to add indexes to existing tables. A multiple-
column index can be created using multiple columns.
The indexes are formed by concatenating the values of the given columns.
CREATE INDEX cannot be used to create a PRIMARY KEY.
Syntax:
CREATE INDEX [index name] ON [table name]([column name]);

Arguments:
Name Description

index name Name of the index.

table name Name of the table.

column name Name of the column.

Example:
CREATE INDEX autid ON newauthor(aut_id);
The above MySQL statement will create an INDEX on 'aut_id' column for 'newauthor' table.

MySQL create UNIQUE INDEX:-


Using CREATE UNIQUE INDEX, you can create an unique index in MySQL.

Example:
CREATE UNIQUE INDEX newautid ON newauthor(aut_id);
The above MySQL statement will create an UNIQUE INDEX on 'aut_id' column for
'newauthor' table.

4. MySQL Sequence:-
In MySQL, a sequence is a list of integers generated in the ascending order i.e., 1,2,3… Many
applications need sequences to generate unique numbers mainly for identification e.g., customer
ID in CRM, employee numbers in HR, equipment numbers in services management system, etc.

Department of Computer Engineering 17


Database Management Systems Lab T.E (Computer Engineering)

To create a sequence in MySQL automatically, set the AUTO_INCREMENT attribute


to a column, which typically is a primary key column.
The following rules are applied when you use the AUTO_INCREMENT attribute:
 Each table has only one AUTO_INCREMENT column whose data type is typically
the integer.
 The AUTO_INCREMENT column must be indexed, which means it can be
either PRIMARY KEY or UNIQUE index.
 The AUTO_INCREMENT column must have a NOT NULL constraint. When you set
the AUTO_INCREMENT attribute to a column, MySQL automatically add the NOT
NULL constraint to the column implicitly.

Example:
The following statement creates a table named employees that has the emp_no column is
an AUTO_INCREMENT column:
CREATE TABLE employees(emp_no INT(4) AUTO_INCREMENT PRIMARY KEY,
first_name VARCHAR(50), last_name VARCHAR(50));

5. MySQL Synonym:-
A synonym is an alias or alternate name for a table, view, sequence, or other schema object.
They are used mainly to make it easy for users to access database objects owned by other users.
Because a synonym is just an alternate name for an object, it requires no storage other than its
definition. When an application uses a synonym, the DBMS forwards the request to the
synonym's underlying base object.
There are two categories of synonyms, public and private.A public synonym can be used
to allow easy access to an object for all system users. In fact, the individual creating a public
synonym does not own the synonym-rather,it will belong to the PUBLIC user group that exists
within Oracle.Private synonyms, on the other hand,belong to the system user that creates them
and reside in that user's schema.
Syntax:
CREATE [PUBLIC|PRIVATE] SYNONYM [synonym name] FOR TABLE|VIEW;

Example:
CREATE SYNONYM emp_syn FOR employees;
The above statement will create a synonym named emp_syn of employees table.

Dropping a Synonym
A user can drop the synonym which it owns. A synonym can be dropped as follows:
DROP SYNONYM emp_syn;

Conclusion: Awareness of Different SQL Objects such as Table, View, Index, Sequence and
Synonym and implemented successfully

Department of Computer Engineering 18


Database Management Systems Lab T.E (Computer Engineering)

ASSIGNMENT NO.: 3

Title: Design atleast 10 SQL queries for suitable database application using SQL DML
statements: Insert, Update, Delete with operators, functions, and set operator.
Objective: To understand the concept of DML statement like Insert, Select, Update, operators
and set operator.
Outcome: Students will be able to execute basic DML commands such as insert, select, update,
delete with operators, functions and set operators.

Requirements:
Software Requirements: Maria DB, Fedora 20, MYSQL
Hardware Requirements: CPU: Intel Core or Xeon 3GHz (or Dual Core 2GHz) or equal
AMD, Cores: Single (Dual/Quad Core is recommended), RAM: 4 GB (6 GBrecommended)

Theory:

DATA MANIPULATION LANGUAGE (DML):


After the database structure is defined with DDL, database administrators and users can utilize
the Data Manipulation Language to insert, retrieve and modify the data contained within it.

1. INSERT Command:
The INSERT command in MYSQL is used to add records to an existing table.

Format 1: Inserting a single row of data into a table.


Syntax:
INSERT INTO TABLE_NAME (column1, column2, column3,...columnN)
VALUES (value1, value2, value3,...valueN);
Example:
The following statement creates a record in the Customers table.
INSERT INTO Customers (Id,Name,Age,Address,Salary) VALUES (1, 'Ramesh', 32,
'Ahmedabad', 2000.00 );

Format 2: Inserting data into a table from another table.


Syntax:
INSERT INTO first_table_name [(column1, column2, ... columnN)]
SELECT column1, column2, ...columnN
FROM second_table_name
[WHERE condition];

2. SELECT Command:
The SELECT statement is used to fetch the data from a database table which returns this data in
the form of a result table. These result tables are called result-sets.
Syntax:
The basic syntax of the SELECT statement is as follows −
SELECT column1, column2, columnN FROM table_name;
Here, column1, column2... are the fields of a table whose values are to be fetched. To fetch all
the records of the table, the following syntax is used:

Department of Computer Engineering 19


Database Management Systems Lab T.E (Computer Engineering)

SELECT * FROM table_name;


Example 1:
The following statement will fetch the ID, Name and Salary fields of the customers available in
Customers table:
SELECT ID, Name, Salary FROM Customers;
Example 2:
All the fields of the Customers table will be fetched by the following query:
SELECT * FROM Customers;

3.UPDATE Command:
The UPDATE command is used to modify the existing records in a table. The WHERE clause
can be used with the UPDATE command to update the selected rows, otherwise all the rows
would be affected.
Syntax:
UPDATE table_name
SET column1 = value1, column2 = value2...., columnN = valueN
WHERE [condition];
Example:
The following query will update the Address for a customer whose ID number is 6 in the table.
UPDATE Customers SET Address = 'Pune' WHERE ID = 6;

4. DELETE Command:
The DELETE command is used to delete the existing records from a table. The WHERE clause
can be used with a DELETE command to delete the selected rows, otherwise all the records
would be deleted.
Syntax:
DELETE FROM table_name WHERE [condition];

Example 1:
The following command will DELETE a customer, whose ID is 6.
DELETE FROM customers WHERE ID = 6;

Example 2:
The following command will delete all the rows from the Customers table −
DELETE FROM Customers;

5. Aggregate Functions:
MySQL aggregate functions retrieve a single value after performing a calculation on a set of
values. In general, aggregate functions ignore null values. Often, aggregate functions are
accompanied by the GROUP BY clause of the SELECT statement.
Following are the MySQL Aggregate Functions:
1) AVG:
The AVG function is used to find the average value.
Syntax:
SELECT AVG(column_name) FROM table_name;
Example:
In the following example the average order amount is displayed from the orders table.
SELECT AVG(amount) FROM orders;
Department of Computer Engineering 20
Database Management Systems Lab T.E (Computer Engineering)

2) SUM:
The SUM function is used to find the sum or total.
Syntax:
SELECT SUM(column_name) FROM table_name;
Example:
In the following example, the sum i.e., total of the order amount will be displayed from the
orders table.
SELECT SUM(amount) FROM orders;

3) MIN:
The MIN function is used to find the minimum value.
Syntax:
SELECT MIN(column_name) FROM table_name;
Example:
In the following example, the minimum order amount will be displayed from the orders table.
SELECT MIN(amount) FROM orders;

4)MAX:
The MAX function is used to find the maximum value.
Syntax:
SELECT MAX(column_name) FROM table_name;
Example:
In the following example, the maximum order amount will be displayed from the orders table:
SELECT MAX(amount) FROM orders;

5)COUNT:
The COUNT function is used to find the number of rows matching the given condition.
Syntax:
SELECT COUNT (column_name) FROM table_name;
Example:
In the following example, we are listing total number of orders in the orders table.
SELECT COUNT(*) FROM orders;

6. Ordering Operation:
The MySQL ORDER BY clause is used to sort the records in your result set.
Syntax:
SELECT expressions FROM tables
[WHERE conditions]
ORDER BY expression [ ASC | DESC ];

Parameters or Arguments:
ASC - Optional. It sorts the result set in ascending order by expression (default, if no modifier
is provider).
DESC - Optional. It sorts the result set in descending order by expression.
Example:
SELECT last_name, first_name, city FROM contacts WHERE last_name = 'Johnson'
ORDER BY city DESC;

Department of Computer Engineering 21


Database Management Systems Lab T.E (Computer Engineering)

The above MySQL ORDER BY example would return all records sorted by the city field in
descending order.

7. Numeric Functions:
MySQL numeric functions are used primarily for numeric manipulation and/or mathematical
calculations.
Function Description
ABS Returns the absolute value of a number
AVG Returns the average value of an expression
CEIL Returns the smallest integer value that is greater than or equal to a number
COS Returns the cosine of a number
COT Returns the cotangent of a number
COUNT Returns the number of records in a select query
DEGREES Converts a radian value into degrees
DIV Used for integer division
EXP Returns e raised to the power of number
FLOOR Returns the largest integer value that is less than or equal to a number
GREATEST Returns the greatest value in a list of expressions
LEAST Returns the smallest value in a list of expressions
LOG Returns the natural logarithm of a number or the logarithm of a number to
a specified base
LOG10 Returns the base-10 logarithm of a number
LOG2 Returns the base-2 logarithm of a number
MAX Returns the maximum value of an expression
MIN Returns the minimum value of an expression
MOD Returns the remainder of n divided by m
PI Returns the value of PI displayed with 6 decimal places
POW Returns m raised to the nth power
POWER Returns m raised to the nth power
RADIANS Converts a value in degrees to radians
ROUND Returns a number rounded to a certain number of decimal places
SIN Returns the sine of a number
SQRT Returns the square root of a number
SUM Returns the summed value of an expression
TAN Returns the tangent of a number
TRUNCATE Returns a number truncated to a certain number of decimal places

8. Date Functions:
MySQL provides many useful date functions that allow you to manipulate date effectively.
1) To get the current date and time, you use NOW() function:
SELECT NOW();
2) To get only date part of a DATETIME value, you use the DATE() function.
SELECT DATE(NOW());
3) To get the current system date, you use CURDATE() function as follows:
SELECT CURDATE();
4) To format a date value, you use DATE_FORMAT function. The following statement
formats the date asmm/dd/yyyy using the date format pattern %m/%d/%Y :
SELECT DATE_FORMAT(CURDATE(), '%m/%d/%Y') today;
Department of Computer Engineering 22
Database Management Systems Lab T.E (Computer Engineering)

8. Set Operations:
SQL supports few Set operations which can be performed on the table data. These are used to get
meaningful results from data stored in the table, under different special conditions.
Types of SET operations:
1. Union
2. Union All
3. Intersect
4. Minus

1. Union
Union is used to combine the results of two or more SELECT statements. However it will
eliminate duplicate rows from its resultset. In case of union, number of columns and datatype
must be same in both the tables, on which UNION operation is being applied.

Fig: Union
Example of Union:
SELECT * FROM First UNION SELECT * FROM Second;

2. Union All
This operation is similar to Union. But it also shows the duplicate rows.

Fig:Union ALL
Example of Union All:
SELECT * FROM First UNION ALL SELECT * FROM Second;

3. Intersect
Intersect operation is used to combine two SELECT statements, but it only retuns the records which
are common from both SELECT statements. In case of Intersect the number of columns and
datatype must be same.
NOTE: MySQL does not support INTERSECT operator.

Fig:Intersect

Department of Computer Engineering 23


Database Management Systems Lab T.E (Computer Engineering)

Example of Intersect:
SELECT * FROM First INTERSECT SELECT * FROM Second;

4. Minus
The Minus operation combines results of two SELECT statements and return only those in the final
result, which belongs to the first set of the result.

Fig:Minus
Example of Minus:
SELECT * FROM First MINUS SELECT * FROM Second;

Conclusion: Implemented all SQL DML commands like Insert, Select, Update, Delete with operators,
functions and set operator.

Department of Computer Engineering 24


Database Management Systems Lab T.E (Computer Engineering)

ASSIGNMENT NO.: 4

Title: Design at least 10 SQL queries for suitable database application using SQL DML statements: all
types of Join, Sub-query and View.
Objective: To understand the concept of DML statements: all types of Join, Sub-query and View.
Outcome: Students will be able to execute basic DML commands: types of Joins, sub-queries and
view.

Requirements:
Software Requirements: Maria DB, Fedora 20, MYSQL
Hardware Requirements: CPU: Intel Core or Xeon 3GHz (or Dual Core 2GHz) or equal AMD,
Cores: Single (Dual/Quad Core is recommended), RAM: 4 GB (6 GB recommended)

Theory:
1. Joins:
SQL Join is used to fetch data from two or more tables, which is joined to appear as single set of
data. It is used for combining column from two or more tables by using values common to both
tables. JOIN Keyword is used in SQL queries for joining two or more tables. Minimum required
condition for joining table, is (n-1) where n, is number of tables. A table can also join to itself,
which is known as, Self Join.
Types of Joins:
Following are the types of JOIN:
1. Inner Join
2. Outer Join
3. Self Join

1.1. Inner Join:


MySQL Inner Joins return all rows from multiple tables where the join condition is met.

Syntax:
SELECT columns FROM table1 INNER JOIN table2
ON table1.column = table2.column;

Visual Illustration:
In the following visual diagram, the MySQL INNER JOIN returns the shaded area:

The MySQL INNER JOIN would return the records where table1 and table2 intersect.
Example:
SELECT suppliers.supplier_id, suppliers.supplier_name, orders.order_date FROM suppliers
INNER JOIN orders ON suppliers.supplier_id = orders.supplier_id;
Department of Computer Engineering 25
Database Management Systems Lab T.E (Computer Engineering)

This MySQL INNER JOIN example would return all rows from the suppliers and orders tables
where there is a matching supplier_id value in both the suppliers and orders tables.

1.2. Outer Join:


Outer Join is based on both matched and unmatched data. Outer Joins subdivide further into,

1) Left Outer Join


2) Right Outer Join
3) Full Outer Join

1) Left Outer Join:

The LEFT JOIN keyword returns all records from the left table (table1), and the matched
records from the right table (table2). The result is NULL from the right side, if there is no
match. In some databases LEFT JOIN is called LEFT OUTER JOIN.

Syntax:

SELECT column_name(s) FROM table1


LEFT JOIN table2 ON table1.column_name = table2.column_name;
Example 1:
SELECT suppliers.supplier_id, suppliers.supplier_name, orders.order_date FROM suppliers
LEFT JOIN orders ON suppliers.supplier_id = orders.supplier_id;

The above LEFT OUTER JOIN example will return all rows from the suppliers table and only
those rows from the orders table where the joined fields are equal. If a supplier_id value in the
suppliers table does not exist in the orders table, all fields in the orders table will display as
<null>in the result set.
Example 2:
Consider a table called suppliers with two fields (supplier_id and supplier_name). It contains
the following data:
supplier_id supplier_name
10000 IBM
10001 Hewlett Packard
10002 Microsoft
10003 NVIDIA

Consider the second table called orders with three fields (order_id, supplier_id, and
order_date). It contains the following data:

Department of Computer Engineering 26


Database Management Systems Lab T.E (Computer Engineering)

order_id supplier_id order_date


500125 10000 2013/05/12
500126 10001 2013/05/13

If run the SELECT statement (that contains a LEFT OUTER JOIN) below:
SELECT suppliers.supplier_id, suppliers.supplier_name, orders.order_date FROM suppliers
LEFT JOIN orders ON suppliers.supplier_id = orders.supplier_id;

The result set will be:


supplier_id supplier_name order_date
10000 IBM 2013/05/12
10001 Hewlett Packard 2013/05/13
10002 Microsoft <null>
10003 NVIDIA <null>

The rows for Microsoft and NVIDIA will be included because a LEFT OUTER JOIN was used.
However, the order_date field for those records contains a <null> value.

2) Right Outer Join:


The RIGHT JOIN keyword returns all records from the right table (table2), and the matched
records from the left table (table1). The result is NULL from the left side, when there is no
match. In some databases RIGHT JOIN is called RIGHT OUTER JOIN.

Syntax:
SELECT column_name(s) FROM table1
RIGHT JOIN table2 ON table1.column_name = table2.column_name;
Example 1:
SELECT orders.order_id, orders.order_date, suppliers.supplier_name FROM suppliers RIGHT
JOIN orders ON suppliers.supplier_id = orders.supplier_id;

This RIGHT OUTER JOIN example will return all rows from the orders table and only those
rows from the suppliers table where the joined fields are equal. If a supplier_id value in the
orders table does not exist in the suppliers table, all fields in the suppliers table will display as
<null> in the result set.

Example 2:
Consider a table called suppliers with two fields (supplier_id and supplier_name). It contains
the following data:

Department of Computer Engineering 27


Database Management Systems Lab T.E (Computer Engineering)

supplier_id supplier_name
10000 Apple
10001 Google

Consider the second table called orders with three fields (order_id, supplier_id, and
order_date). It contains the following data:

order_id supplier_id order_date


500125 10000 2013/08/12
500126 10001 2013/08/13
500127 10002 2013/08/14

If run the SELECT statement (that contains a RIGHT OUTER JOIN) below:
SELECT orders.order_id, orders.order_date, suppliers.supplier_name FROM suppliers RIGHT
JOIN orders ON suppliers.supplier_id = orders.supplier_id;

The result set will be:


order_id order_date supplier_name
500125 2013/08/12 Apple
500126 2013/08/13 Google
500127 2013/08/14 <null>

The row for 500127 (order_id) will be included because a RIGHT OUTER JOIN was used.
However, the supplier_name field for that record will contain a <null> value.

3) Full Outer Join:


The FULL OUTER JOIN keyword return all records when there is a match in either left
(table1) or right (table2) table records. FULL OUTER JOIN can potentially return very large
result-sets.

Syntax:
SELECT column_name(s) FROM table1
FULL OUTER JOIN table2 ON table1.column_name = table2.column_name;

Example:
Consider the following two tables:
Table 1 − CUSTOMERS Table is as follows:

Department of Computer Engineering 28


Database Management Systems Lab T.E (Computer Engineering)

+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+
Table 2 − ORDERS Table is as follows.
+-----+---------------------+-------------+--------+
|OID | DATE | CUSTOMER_ID | AMOUNT |
+-----+---------------------+-------------+--------+
| 102 | 2009-10-08 00:00:00 | 3 | 3000 |
| 100 | 2009-10-08 00:00:00 | 3 | 1500 |
| 101 | 2009-11-20 00:00:00 | 2 | 1560 |
| 103 | 2008-05-20 00:00:00 | 4 | 2060 |
+-----+---------------------+-------------+--------+
Now, let us join these two tables using FULL JOIN as follows.

SELECT ID, NAME, AMOUNT, DATE FROM CUSTOMERS FULL JOIN ORDERS ON
CUSTOMERS.ID = ORDERS.CUSTOMER_ID;

This would produce the following result −


+------+----------+--------+---------------------+
| ID | NAME | AMOUNT | DATE |
+------+----------+--------+---------------------+
| 1 | Ramesh | NULL | NULL |
| 2 | Khilan | 1560 | 2009-11-20 00:00:00 |
| 3 | kaushik | 3000 | 2009-10-08 00:00:00 |
| 3 | kaushik | 1500 | 2009-10-08 00:00:00 |
| 4 | Chaitali | 2060 | 2008-05-20 00:00:00 |
| 5 | Hardik | NULL | NULL |
| 6 | Komal | NULL | NULL |
| 7 | Muffy | NULL | NULL |
| 3 | kaushik | 3000 | 2009-10-08 00:00:00 |
| 3 | kaushik | 1500 | 2009-10-08 00:00:00 |
| 2 | Khilan | 1560 | 2009-11-20 00:00:00 |
| 4 | Chaitali | 2060 | 2008-05-20 00:00:00 |
+------+----------+--------+---------------------+

Note: MySQL does not support FULL JOIN. In this case, use UNION ALL clause to combine
these two JOINS as shown below:

SELECT ID, NAME, AMOUNT, DATE FROM CUSTOMERS LEFT JOIN ORDERS ON
CUSTOMERS.ID = ORDERS.CUSTOMER_ID UNION ALL SELECT ID, NAME, AMOUNT,
DATE FROM CUSTOMERS RIGHT JOIN ORDERS ON CUSTOMERS.ID =
ORDERS.CUSTOMER_ID

Department of Computer Engineering 29


Database Management Systems Lab T.E (Computer Engineering)

3) Self Join:A self JOIN is a regular join, but the table is joined with itself.
Syntax:
SELECT column_name(s) FROM table1 T1, table1 T2 WHERE condition;
Example:
Consider the following table.
CUSTOMERS Table is as follows:
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+

Now, joining this table using SELF JOIN is as follows −


SELECT a.ID, b.NAME, a.SALARY FROM CUSTOMERS a, CUSTOMERS b WHERE
a.SALARY < b.SALARY;

This will produce the following result –


+----+----------+---------+
| ID | NAME | SALARY |
+----+----------+---------+
| 2 | Ramesh | 1500.00 |
| 2 | kaushik | 1500.00 |
| 1 | Chaitali | 2000.00 |
| 2 | Chaitali | 1500.00 |
| 3 | Chaitali | 2000.00 |
| 6 | Chaitali | 4500.00 |
| 1 | Hardik | 2000.00 |
| 2 | Hardik | 1500.00 |
| 3 | Hardik | 2000.00 |
| 4 | Hardik | 6500.00 |
| 6 | Hardik | 4500.00 |
| 1 | Komal | 2000.00 |
| 2 | Komal | 1500.00 |
| 3 | Komal | 2000.00 |
| 1 | Muffy | 2000.00 |
| 2 | Muffy | 1500.00 |
| 3 | Muffy | 2000.00 |
| 4 | Muffy | 6500.00 |
| 5 | Muffy | 8500.00 |
| 6 | Muffy | 4500.00 |

Department of Computer Engineering 30


Database Management Systems Lab T.E (Computer Engineering)

1.3. View:
View is a data object which does not contain any data. Contents of the view are the resultant of a
base table. They are operated just like base table but they don’t contain any data of their own. The
difference between a view and a table is that views are definitions built on top of other tables (or
views). If data is changed in the underlying table, the same change is reflected in the view. A view
can be built on top of a single or multiple tables.

1) Creating View:
Syntax:
CREATE [OR REPLACE] VIEW view_name AS SELECT columns FROM tables [WHERE
conditions];
Example:
CREATE VIEW hardware_suppliers AS SELECT supplier_id, supplier_name FROM suppliers
WHERE category_type = 'Hardware';
This CREATE VIEW example would create a virtual table based on the result set of the SELECT
statement. You can now query the MySQL VIEW as follows:
SELECT * FROM hardware_suppliers;

2) Create View with Join:


CREATE VIEW command can be used along with a JOIN statement.
Example:
CREATE VIEW view_purchase AS SELECT a.cate_id,a.cate_descrip, b.invoice_no,
b.invoice_dt,b.book_name FROM category a,purchase b WHERE a.cate_id=b.cate_id;
The above MySQL statement will create a view 'view_purchase' along with a JOIN statement. The
JOIN statement here retrieves cate_id, cate_descrip from category table and invoice_no, invoice_dt,
and book_name from purchase table if cate_id of category table and that of purchase are same.

3) View with Sub-query:


CREATE VIEW command can be used with subqueries.
Example:
CREATE VIEW view_purchase AS SELECT invoice_no,book_name,cate_id
FROM purchase
WHERE cate_id=(SELECT cate_id FROM book_mast WHERE no_page=201);

The above MySQL statement will create a view 'view_purchase' taking all the records of
invoice_no, book_name and cate_id columns of purchase table, if category id (cate_id) satisfies the
condition defined within a subquery (followed by cate_id=).
The subquery retrieves only cate_ids from book_mast table, which contain books with 201 pages.

5) Alter a View:
The definition of a VIEW in MySQL can be modified without dropping it by using the ALTER
VIEW statement.
Syntax:
ALTER VIEW view_name AS SELECT columns FROM table WHERE conditions;
Example:
ALTER VIEW hardware_suppliers AS SELECT supplier_id, supplier_name, address, city
FROM suppliers WHERE category_type = 'Hardware';

Department of Computer Engineering 31


Database Management Systems Lab T.E (Computer Engineering)

This ALTER VIEW example in MySQL would update the definition of the VIEW
called hardware_suppliers without dropping it. In this example, we are adding
the address and city columns to the VIEW.

4) Drop View:
Once a VIEW has been created in MySQL, it can be dropped or deleted with the DROP VIEW
statement.
Syntax:
DROP VIEW [IF EXISTS] view_name;
Example:
DROP VIEW hardware_suppliers;
This DROP VIEW example will drop/delete the MySQL VIEW called hardware_suppliers.

1.4. Sub-queries:
In MySQL, a subquery is a query within a query. You can create subqueries within your SQL
statements. These subqueries can reside in the WHERE clause, the FROM clause, or the SELECT
clause.
The main advantages of subqueries are:

 They allow queries that are structured so that it is possible to isolate each part of a statement.
 They provide alternative ways to perform operations that would otherwise require complex
joins and unions.
 Many people find subqueries more readable than complex joins or unions. Indeed, it was the
innovation of subqueries that gave people the original idea of calling the early SQL “Structured
Query Language.”

Example:
SELECT * FROM t1 WHERE column1 = (SELECT column1 FROM t2);
In this example, SELECT * FROM t1 ... is the outer query (or outer statement), and (SELECT
column1 FROM t2) is the subquery. We say that the subquery is nested within the outer query, and
in fact it is possible to nest subqueries within other subqueries, to a considerable depth. A subquery
must always appear within parentheses.

1) Subqueries in the WHERE clause:


Most often, the subquery will be found in the WHERE clause. These subqueries are also called
nested subqueries.
Example:
SELECT c.contact_id, c.last_name
FROM contacts c
WHERE c.site_name IN
(SELECT a.site_name
FROM address_book a
WHERE a.address_book_id < 50);
The subquery portion of the SELECT statement above is:
(SELECT a.site_name

Department of Computer Engineering 32


Database Management Systems Lab T.E (Computer Engineering)

FROM address_book a

WHERE a.address_book_id < 50);


This subquery will find all site_name values from the address_book table that have
an address_book_id less than 50.

2) Subqueries in FROM clause:


A subquery can also be found in the FROM clause. These are called inline views.
Example:
SELECT contacts.last_name, subquery1.total_size FROM contacts, (SELECT site_name,
SUM(file_size) AS total_size FROM pages GROUP BY site_name) subquery1 WHERE
subquery1.site_name = contacts.site_name;
In this example, a subquery has been created in the FROM clause as follows:
(SELECT site_name, SUM(file_size) AS total_size FROM pages GROUP BY site_name)
subquery1
This subquery has been aliased with the name subquery1. This will be the name used to reference
this subquery or any of its fields.

3) Using subquery to return one or more rows of values:


A subquery that returns one or more rows of values is also known as row subquery. A row
subquery is a subquery variant that returns one or more rows and can thus return more than one
column value.
Example:
select EmployeeID, FirstName, LastName, City, Country
from employees
where row(City, Country) in
(select City, Country from customers);

This query finds out all the employees who live in the same city and country as customers.
The subquery returns a table of two columns. It's returned to outer query and City and Country in
employees table are compared with each row in the table.

4) Update command with subquery:


A subquery can be used to update the values of columns with the UPDATE statement.
Example:
UPDATE Articles
SET ArticleTitle='The Way of Zen', Copyright=1957
WHERE ArticleID=
(
SELECT ab.ArticleID
FROM Authors AS a, AuthorArticle AS ab
WHERE a.AuthID=ab.AuthID AND a.AuthorLastName='Yin'
);

Department of Computer Engineering 33


Database Management Systems Lab T.E (Computer Engineering)

5) Delete command with subquery:


To delete records in a table based on values that are stored in other database tables, a subquery
within a DELETE statement can be used.
Example:
mysql> DELETE ab, b
-> FROM AuthorBook AS ab, Books AS b
-> WHERE ab.BookID=b.BookID
-> AND ab.AuthID=(SELECT AuthID FROM Authors WHERE AuthLN='A');

Conclusion: Thus have implemented SQL DML statements: all types of Joins, Sub-query and
View successfully.

Department of Computer Engineering 34


Database Management Systems Lab T.E (Computer Engineering)

ASSIGNMENT NO: 5
Title: Unnamed PL/SQL code block: Use of Control structure and Exception handling is mandatory.
Write a PL/SQL block of code for the following requirements: - Schema:
1. Borrower (Rollin, Name, DateofIssue, NameofBook, Status)
2. Fine (Roll_no,Date,Amt)
 Accept roll_no& name of book from user.
 Check the number of days (from date of issue), if days are between 15 to 30 then fine amounts
will be Rs 5per day.
 If no. of days>30, per day fine will be Rs 50 per day & for days less than 30, Rs. 5 per day.
 After submitting the book, status will change from I to R.
 If condition of fine is true, then details will be stored into fine table.
Frame the problem statement for writing PL/SQL block in line with above statement.

Objective: Understand the concept of Unnamed PL/SQL code, different Control Structure and
exception handling.

Requirements:
Software Requirements: Maria DB, Fedora 20, MYSQL
Hardware Requirements: CPU: Intel Core or Xeon 3GHz (or Dual Core 2GHz) or equal AMD,
Cores: Single (Dual/Quad Core is recommended), RAM: 4 GB (6 GB recommended)

Theory:

Introducing PL/SQL block structure and anonymous block


PL/SQL program units organize the code into blocks. A block without a name is known as an
anonymous block. The anonymous block is the simplest unit in PL/SQL. It is called anonymous block
because it is not saved in the Oracle database.An anonymous block is an only one-time use and useful
in certain situations such as creating test units. The following illustrates anonymous block syntax:
[DECLARE]
Declaration statements;
BEGIN
Execution statements;
[EXCEPTION]
Exception handling statements;
END;
/

The anonymous block has three basic sections that are the declaration, execution, and exception
handling. Only the execution section is mandatory and the others are optional.

Department of Computer Engineering 35


Database Management Systems Lab T.E (Computer Engineering)

 The declaration section allows you to define data types, structures, and variables. You often
declare variables in the declaration section by giving those names, data types, and initial values.
 The execution section is required in a block structure and it must have at least one statement.
The execution section is the place where you put the execution code or business logic code.
You can use both procedural and SQL statements inside the execution section.
 The exception handling section is starting with the EXCEPTIONkeyword. The exception
section is the place that you put the code to handle exceptions. You can either catch or handle
exceptions in the exception section.

IF- Statement:The IF statement executes a sequence of statements depending on the value of a


condition.

Syntax:
IFcondition THEN statement1;
ElSEIF condition2 THEN statement2;
ENDIF;

Using the LOOP Statement:


The simplest form of LOOP statement is the basic loop, which encloses a sequence of statements
between the keywords LOOP and END LOOP, as follows:
LOOP
sequence_of_statements
END LOOP;

With each iteration of the loop, the sequence of statements is executed, then control resumes at the top
of the loop. You use an EXIT statement to stop looping and prevent an infinite loop. You can place one
Department of Computer Engineering 36
Database Management Systems Lab T.E (Computer Engineering)

or more EXIT statements anywhere inside a loop, but not outside a loop. There are two forms
of EXIT statements: EXIT and EXIT-WHEN.

Exception:
PL/SQL supports programmers to catch such conditions using EXCEPTION block in the program and
an appropriate action is taken against the error condition. There are two types of exceptions
1. System-defined exceptions
2. User-defined exceptions

Syntax for Exception Handling:


DECLARE
Declaration section
BEGIN
Exception section
EXCEPTION
WHEN ex_name1 THEN
-Error handling statements
WHEN ex_name2 THEN
-Error handling statements
WHEN Others THEN
-Error handling statements
END;

Raising Exception:
Exception are raised by the database server automatically whenever there is any internal database error,
but exception can be raised explicitly by the programmer by using the command RAISE. Following is
the syntax for raising an exception.

Syntax:
DECLARE
Exception_name EXCEPTION;
BEGIN
IF condition THEN
RAISE exception_name;
ENDIF;
EXCEPTION
WHEN exception_name THEN
STATEMENT

User-defined Exceptions:
Steps to be followed to use user-defined exceptions:
• They should be explicitly declared in the declaration section.

• They should be explicitly raised in the Execution Section.


• They should be handled by referencing the user-defined exception name in the exception section.

Department of Computer Engineering 37


Database Management Systems Lab T.E (Computer Engineering)

Program:
[sinhgad@localhost ~]$ su
Password:
[root@localhostsinhgad]# mysql
Welcome to the MariaDB monitor. Commands end with ; or \g.
Your MariaDB connection id is 6
Server version: 5.5.43-MariaDB MariaDB Server
Copyright (c) 2000, 2015, Oracle, MariaDB Corporation Ab and others.
Type 'help;' or '\h' for help.Type '\c' to clear the current input statement.
MariaDB [(none)]> use test;
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A
Database changed
MariaDB [test]> create table Fine(Roll int(2),CurrentDatedate,Amtint(3));
Query OK, 1 row affected (0.01 sec)
MariaDB [test]> create table borrower(Roll int(2),SNamevarchar(10),dateofissuedate,booknamevarchar(10),status
varchar(4));
Query OK, 0 row affected (0.02 sec)
MariaDB [test]> insert into borrower values(1,'Maya','2018-06-09','DBMS','No');
Query OK, 1 row affected (0.01 sec)

MariaDB [test]> insert into borrower values(2,'Kavya','2018-01-09','SEPM','I');


Query OK, 1 row affected (0.01 sec)

MariaDB [test]> insert into borrower values(3,'RIYA','2018-02-09','ISEE','I');


Query OK, 1 row affected (0.01 sec)

MariaDB [test]> insert into borrower values(4,'Priya','2018-04-09','TOC','I');


Query OK, 1 row affected (0.02 sec)

MariaDB [test]> select * from borrower;


+------+-------+-------------+----------+--------+
| Roll | SName | dateofissue | bookname | status |
+------+-------+-------------+----------+--------+
| 1 | Maya | 2018-06-09 | DBMS | No |
| 2 |Kavya | 2018-01-09 | SEPM | I |
| 3 | RIYA | 2018-02-09 | ISEE | I |
| 4 | Priya | 2018-04-09 | TOC | I |
+------+-------+-------------+----------+--------+
4 rows in set (0.00 sec)

MariaDB [test]> delimiter #


MariaDB [test]> create procedure fine(IN rollnoint,INbnamevarchar(20))
-> begin
-> declare B_Issue_Date date;
-> declare Days int(4);
-> declare fine_amtint(4);
-> declare temp int(4);
->selectdateofissue into B_Issue_Date from borrower where Roll=rollno and BookName=bname;
->set Days=curdate()- B_Issue_Date;
->if(Days<=15)
->then
->setfine_amt=0;
-> select 'No fine';

->elseif(Days>30 && Days<60) then


->set temp=Days-15;

Department of Computer Engineering 38


Database Management Systems Lab T.E (Computer Engineering)

->setfine_amt=temp*5;
->insert into Fine values(rollno,curdate(),fine_amt);
->else
->set temp=Days-30;
->setfine_amt=(temp*50)+(15*5);
->insert into Fine values(rollno,curdate(),fine_amt);
->end if;
->end;
-> #
Query OK, 0 rows affected (0.08 sec)

MariaDB [test]> delimiter #


MariaDB [test]> call fine(1,'DBMS');
-> #
Query OK, 1 row affected (0.03 sec)

MariaDB [test]> select * from Fine;


-> #
+------+-------------+------+
| Roll | CurrentDate | Amt |
+------+-------------+------+
| 1 | 2018-07-12 | 3725 |
+------+-------------+------+
1 row in set (0.00 sec)

MariaDB [test]> delimiter #


MariaDB [test]> call fine(4,'TOC');
-> #
Query OK, 1 row affected (0.02 sec)

MariaDB [test]> select * from Fine;


-> #
+------+-------------+-------+
| Roll | CurrentDate | Amt |
+------+-------------+-------+
| 1 | 2018-07-12 | 3725 |
| 4 | 2018-07-12 | 13725 |
+------+-------------+-------+
2 rows in set (0.00 sec)

MariaDB [test]> insert into borrower Values (5,'Piya','2018-08-22','ADSL','NO');


-> #
Query OK, 1 row affected (0.02 sec)

MariaDB [test]> select * from borrower;


-> #
+------+-------+-------------+----------+--------+
| Roll | SName | dateofissue | bookname | status |
+------+-------+-------------+----------+--------+
| 1 | Maya | 2018-06-09 | DBMS | No |
| 2 | Kavya | 2018-01-09 | SEPM | I |
| 3 | RIYA | 2018-02-09 | ISEE | I |
| 4 | Priya | 2018-04-09 | TOC | I |
| 5 | Piya | 2018-08-22 | ADSL | NO |
+------+-------+-------------+----------+--------+
5 rows in set (0.00 sec)

Department of Computer Engineering 39


Database Management Systems Lab T.E (Computer Engineering)

MariaDB [test]> delimiter #


MariaDB [test]> call fine(5,'ADSL');
-> #
+---------+
| No fine |
+---------+
| No fine |
+---------+
1 row in set (0.00 sec)

Query OK, 0 rows affected (0.00 sec)

MariaDB [test]> select * from Fine;


-> #
+------+-------------+-------+
| Roll | CurrentDate | Amt |
+------+-------------+-------+
| 1 | 2018-07-12 | 3725 |
| 4 | 2018-07-12 | 13725 |
+------+-------------+-------+
2 rows in set (0.00 sec)

MariaDB [test]> insert into borrower Values (6,'praniti','2018-08-22','MICRO','I');


-> #
Query OK, 1 row affected (0.02 sec)

MariaDB [test]> select * from borrower;


-> #
+------+---------+-------------+----------+--------+
| Roll | SName | dateofissue | bookname | status |
+------+---------+-------------+----------+--------+
| 1 | Maya | 2018-06-09 | DBMS | No |
| 2 | Kavya | 2018-01-09 | SEPM | I |
| 3 | RIYA | 2018-02-09 | ISEE | I |
| 4 | Priya | 2018-04-09 | TOC | I |
| 5 | Piya | 2018-08-22 | ADSL | NO |
| 6 | praniti | 2018-08-22 | MICRO | I |
+------+---------+-------------+----------+--------+
6 rows in set (0.00 sec)

MariaDB [test]> delimiter @


MariaDB [test]> create procedure fine11(IN rollnoint,INbnamevarchar(20))
-> begin
-> declare B_Issuse_Date date;
-> declare Days int(4);
-> declare fine_amtint(4);
-> declare temp int(4);
->selectdateofissue into B_Issuse_Date from borrower
->where Roll = rollno and BookName = bname;
->set Days=curdate()- B_Issuse_Date;
->if(Days<=15)
->then
->setfine_amt=0;
-> select 'No fine';
->elseif (Days>30 && Days<60) then
->set temp=Days-15;
->setfine_amt=temp*5;

Department of Computer Engineering 40


Database Management Systems Lab T.E (Computer Engineering)

->insert into Fine values(rollno,curdate(),fine_amt);

->else
->set temp=Days-30;
->setfine_amt=(temp*50)+(15*5);
->insert into Fine values(rollno,curdate(),fine_amt);
->end if;
->end;
-> @
Query OK, 0 rows affected (0.00 sec)

MariaDB [test]> delimiter #


MariaDB [test]> call fine11(5,'ADSL');
-> #
+---------+
| No fine |
+---------+
| No fine |
+---------+
1 row in set (0.00 sec)

Query OK, 0 rows affected (0.00 sec)

MariaDB [test]> call fine11(6,'MICRO');


-> #
+---------+
| No fine |
+---------+
| No fine |
+---------+
1 row in set (0.00 sec)

Query OK, 0 rows affected (0.00 sec)

MariaDB [test]> select * from Fine;


-> #
+------+-------------+-------+
| Roll | CurrentDate | Amt |
+------+-------------+-------+
| 1 | 2018-07-12 | 3725 |
| 4 | 2018-07-12 | 13725 |
+------+-------------+-------+
2 rows in set (0.00 sec)

MariaDB [test]> delimiter $


MariaDB [test]> create procedure f()
-> begin
->update borrower
->set status='R' where status='I';
->end;
-> $
Query OK, 0 rows affected (0.00 sec)

MariaDB [test]> delimiter $


MariaDB [test]> call f();
-> $
Query OK, 4 rows affected (0.02 sec)

Department of Computer Engineering 41


Database Management Systems Lab T.E (Computer Engineering)

MariaDB [test]> select * from borrower;


-> $

+------+---------+-------------+----------+--------+
| Roll | SName | dateofissue | bookname | status |
+------+---------+-------------+----------+--------+
| 1 | Maya | 2018-06-09 | DBMS | No |
| 2 | Kavya | 2018-01-09 | SEPM | R |
| 3 | RIYA | 2018-02-09 | ISEE | R |
| 4 | Priya | 2018-04-09 | TOC | R |
| 5 | Piya | 2018-08-22 | ADSL | NO |
| 6 | praniti| 2018-08-22 | MICRO | R |
+------+---------+-------------+----------+--------+
6 rows in set (0.00 sec)

Conclusion: Successfully implemented the PL/SQL code with proper understanding of different
control structure and exception handling.

Department of Computer Engineering 42


Database Management Systems Lab T.E (Computer Engineering)

ASSIGNMENT NO: 6

Title: Cursors: (All types: Implicit, Explicit, Cursor FOR Loop, Parameterized Cursor)
Write a PL/SQL block of code using parameterized Cursor that will merge the data available in the
newly created table N_RollCall with the data available in the table O_RollCall. If the data in the first
table already exist in the second table then that data should be skipped.
Objective: To study cursor PL/SQL block of code.

Requirements:
Software Requirements: Maria DB, Fedora 20, MYSQL
Hardware Requirements: CPU: Intel Core or Xeon 3GHz (or Dual Core 2GHz) or equal AMD,
Cores: Single (Dual/Quad Core is recommended), RAM: 4 GB (6 GB recommended)

Theory:

PL/SQL Cursor
When an SQL statement is processed, Oracle creates a memory area, known as the context area, for
processing an SQL statement, which contains all the information needed for processing the statement;
for example, the number of rows processed, etc.
A cursor is a pointer to this context area. PL/SQL controls the context area through a cursor. A
cursor holds the rows (one or more) returned by a SQL statement. The set of rows the cursor holds is
referred to as the active set. You can name a cursor so that it could be referred to in a program to fetch
and process the rows returned by the SQL statement, one at a time. There are two types of cursors
Declare a Cursor:
Description
A cursor is a SELECT statement that is defined within the declaration section of PL/SQL code. The
three different syntaxes to declare a cursor.

1. Cursor without parameters (simplest)


Declaring a cursor without any parameters is the simplest cursor.
Syntax:
The syntax for a cursor without parameters in PL/SQL is:

CURSOR cursor_name
IS
SELECT_statement;

2. Cursor with parameters


Syntax:
The syntax for a cursor with parameters in PLSQL is:
CURSOR cursor_name (parameter_list)
IS
SELECT_statement;

Department of Computer Engineering 43


Database Management Systems Lab T.E (Computer Engineering)

3. Cursor with return clause


Syntax
The syntax for a cursor with a return clause in PLSQL is:

CURSOR cursor_name
RETURN field%ROWTYPE
IS
SELECT_statement;

 Implicit cursors
 Explicit cursors

1) PL/SQL Implicit cursor:


Implicit cursors are automatically created by Oracle whenever an SQL statement is executed, when
there is no explicit cursor for the statement. Programmers cannot control the implicit cursors and the
information in it.
Whenever a DML statement (INSERT, UPDATE and DELETE) is issued, an implicit cursor is
associated with this statement. For INSERT operations, the cursor holds the data that needs to be
inserted. For UPDATE and DELETE operations, the cursor identifies the rows that would be
affected. In PL/SQL, you can refer to the most recent implicit cursor as the SQL cursor, which
always has attributes such as %FOUND, %ISOPEN, %NOTFOUND, and %ROWCOUNT.
S.No Attribute & Description

%FOUND
1
Returns TRUE if an INSERT, UPDATE, or DELETE statement affected one or more rows or a SELECT INTO statement
returned one or more rows. Otherwise, it returns FALSE.

%NOTFOUND

2 The logical opposite of %FOUND. It returns TRUE if an INSERT, UPDATE, or DELETE statement affected no rows, or a
SELECT INTO statement returned no rows. Otherwise, it returns FALSE.

%ISOPEN

3 Always returns FALSE for implicit cursors, because Oracle closes the SQL cursor automatically after executing its associated
SQL statement.

%ROWCOUNT

4 Returns the number of rows affected by an INSERT, UPDATE, or DELETE statement, or returned by a SELECT INTO
statement.

Department of Computer Engineering 44


Database Management Systems Lab T.E (Computer Engineering)

2) PL/SQL Explicit Cursors:


Explicit cursors are programmer-defined cursors for gaining more control over the context area. An
explicit cursor should be defined in the declaration section of the PL/SQL Block. It is created on a
SELECT Statement which returns more than one row.
The syntax for creating an explicit cursor is −

CURSOR cursor_name IS select_statement;


Working with an explicit cursor includes the following steps :=

 Declaring the cursor for initializing the memory


 Opening the cursor for allocating the memory
 Fetching the cursor for retrieving the data
 Closing the cursor to release the allocated memory
Declaring the Cursor
Declaring the cursor defines the cursor with a name and the associated SELECT statement. For
example:

CURSOR C_name IS
SELECT statement;

Opening the Cursor


Opening the cursor allocates the memory for the cursor and makes it ready for fetching the rows
returned by the SQL statement into it.

OPEN C_name;

Fetching the Cursor


Fetching the cursor involves accessing one row at a time.

FETCH C_name INTO variable list;

Closing the Cursor


Closing the cursor means releasing the allocated memory.

CLOSE C_name;
Working with MySQL cursor

First, declare a cursor by using the DECLARE statement:


DECLARE cursor_name CURSOR FOR SELECT_statement;

The cursor declaration must be after any variable declaration. If declare a cursor before variables
declaration, MySQL will issue an error. A cursor must always be associated with a SELECT statement.

Department of Computer Engineering 45


Database Management Systems Lab T.E (Computer Engineering)

Next, open the cursor by using the OPEN statement. The OPEN statement initializes the result set
for the cursor; therefore, call the OPEN statement before fetching rows from the result set.
OPEN cursor_name;

Then, use the FETCH statement to retrieve the next row pointed by the cursor and move the
cursor to the next row in the result set.
FETCH cursor_name INTO variables list;

After that, check to see if there is any row available before fetching it. Finally, call
the CLOSE statement to deactivate the cursor and release the memory associated with it as follows:
CLOSE cursor_name;
When the cursor is no longer used, close it.
When working with MySQL cursor, also declare a NOT FOUND handler to handle the situation when
the cursor could not find any row. Because each time call the FETCH statement, the cursor attempts to
read the next row in the result set. When the cursor reaches the end of the result set, it will not be able
to get the data, and a condition is raised. The handler is used to handle this condition.
To declare a NOT FOUND handler, use the following syntax:
DECLARE CONTINUE HANDLER FOR NOT FOUND SET finished = 1;

The finished is a variable to indicate that the cursor has reached the end of the result set. Notice that the
handler declaration must appear after variable and cursor declaration inside the stored procedures.
The following diagram illustrates how MySQL cursor works.

MySQL Cursor Example

To develop a stored procedure that builds an email list of all employees in the employeestable in
the sample database. First, declare some variables, a cursor for looping over the emails of employees,
and a NOT FOUNDhandler:

DELIMITER $$
CREATE PROCEDURE build_email_list (INOUT email_list varchar(4000))
BEGIN
DECLARE v_finished INTEGER DEFAULT 0;
DECLARE v_email varchar(100) DEFAULT "";
-- declare cursor for employee email
DEClARE email_cursor CURSOR FOR
SELECT email FROM employees;
-- declare NOT FOUND handler
DECLARE CONTINUE HANDLER

Department of Computer Engineering 46


Database Management Systems Lab T.E (Computer Engineering)

FOR NOT FOUND SET v_finished = 1;


OPEN email_cursor;
get_email: LOOP
FETCH email_cursor INTO v_email;
IF v_finished = 1 THEN
LEAVE get_email;
END IF;
-- build email list
SET email_list = CONCAT(v_email,";",email_list);
END LOOP get_email;
CLOSE email_cursor;
END$$
DELIMITER ;

Program:
[sinhgad@localhost ~]$ su
Password:
[root@localhost sinhgad]# mysql
Welcome to the MariaDB monitor. Commands end with ; or \g.
Your MariaDB connection id is 4

Server version: 5.5.43-MariaDB MariaDB Server


Copyright (c) 2000, 2015, Oracle, MariaDB Corporation Ab and others.
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

MariaDB [(none)]> use stud;


Database changed

MariaDB [stud]> create table stud_marks(rollno int(2),name varchar(12),total_marks int(12));


Query OK, 0 rows affected (0.06 sec)

MariaDB [stud]> insert into stud_marks values(1,"Ravi",933),(2,"sagar",450),(3,"sarita",1300),(4,"avi",250),(5,"raj",675);

Query OK, 5 rows affected (0.02 sec)


Records: 5 Duplicates: 0 Warnings: 0

MariaDB [stud]> select * from stud_marks;

+--------+--------+-------------+
| rollno | name | total_marks |
+--------+--------+-------------+
| 1 | Ravi | 933 |
| 2 | sagar | 450 |
| 3 | sarita | 1300 |
| 4 | avi | 250 |
| 5 | raj | 675 |
+--------+--------+-------------+
5 rows in set (0.00 sec)

MariaDB [stud]> create table new_stud_marks(roll_no int(2),name char(10),grade char(10));


Query OK, 0 rows affected (0.04 sec)

MariaDB [stud]> delimiter //


MariaDB [stud]> CREATE PROCEDURE grade1()

Department of Computer Engineering 47


Database Management Systems Lab T.E (Computer Engineering)

-> BEGIN
-> DECLARE rolln INT;
-> DECLARE stu_name CHAR(50);
-> DECLARE marks INT;
-> DECLARE done INT DEFAULT FALSE;
-> DECLARE cur1 CURSOR FOR SELECT rollno,name,total_marks FROM stud_marks;
-> DECLARE CONTINUE HANDLER FOR NOT FOUND SET done=TRUE;
-> OPEN cur1;
-> read_loop:LOOP
-> FETCH cur1 INTO rolln,stu_name,marks;
-> IF done THEN
-> LEAVE read_loop;
-> END IF;
-> IF(marks>=990 AND marks<=1500)THEN

-> INSERT INTO new_stud_marks values(rolln,stu_name,'DISTINCTION');


-> ELSEIF(marks>=900 AND marks<=989)THEN
-> INSERT INTO new_stud_marks values(rolln,stu_name,'FIRST CLASS');
-> ELSEIF(marks>=825 AND marks<=899)THEN
-> INSERT INTO new_stud_marks values(rolln,stu_name,'SECOND CLASS');
-> ELSE
-> INSERT INTO new_stud_marks values(rolln,stu_name,'FAIL');
-> END IF;
-> END LOOP;
-> CLOSE cur1;

-> END //

Query OK, 0 rows affected (0.00 sec)

MariaDB [stud]> delimiter ;


MariaDB [stud]> describe stud_marks;
+-------------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------------+-------------+------+-----+---------+-------+
| rollno | int(2) | YES | | NULL | |
| name | varchar(12) | YES | | NULL | |
| total_marks | int(12) | YES | | NULL | |
+-------------+-------------+------+-----+---------+-------+
3 rows in set (0.01 sec)

MariaDB [stud]> select * from stud_marks;


+--------+--------+-------------+
| rollno | name | total_marks |
+--------+--------+-------------+
| 1 | Ravi | 933 |
| 2 | sagar | 450 |
| 3 | sarita | 1300 |
| 4 | avi | 250 |
| 5 | raj | 675 |
+--------+--------+-------------+
5 rows in set (0.00 sec)

MariaDB [stud]> describe new_stud_marks;


+---------+----------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+---------+----------+------+-----+---------+-------+

Department of Computer Engineering 48


Database Management Systems Lab T.E (Computer Engineering)

| roll_no | int(2) | YES | | NULL | |


| name | char(10) | YES | | NULL | |
| grade | char(10) | YES | | NULL | |
+---------+----------+------+-----+---------+-------+
3 rows in set (0.00 sec)

MariaDB [stud]> select * from new_stud_marks;


Empty set (0.00 sec)

MariaDB [stud]> call grade1;


Query OK, 0 rows affected, 0 warning (0.05 sec)

MariaDB [stud]> select * from new_stud_marks;


+---------+--------+------------+
| roll_no | name | grade |
+---------+--------+------------+
| 1 | Ravi | FIRST CLAS |
| 2 | sagar | FAIL |
| 3 | sarita | DISTINCTIO |
| 4 | avi | FAIL |
| 5 | raj | FAIL |
+---------+--------+------------+
5 rows in set (0.00 sec)

Conclusion: Implemented the PL/SQL block of code using the cursor.

Department of Computer Engineering 49


Database Management Systems Lab T.E (Computer Engineering)

ASSIGNMENT NO.: 7

Title: PL/SQL Stored Procedure and Stored Function.


Write a Stored Procedure namely proc_Grade for the categorization of student. If marks scored by
students in examination is <=1500 and marks>=990 then student will be placed in distinction category
if marks scored are between 989 and900 category is first class, if marks 899 and 825 category is Higher
Second Class
Write a PL/SQL block for using procedure created with above requirement. Stud_Marks(name,
total_marks) Result(Roll,Name, Class).Frame the separate problem statement for writing PL/SQL
Stored Procedure and function, in line with above statement. The problem statement should clearly
state the requirements.

Objective: 1) To understand the difference between procedure and function


2) To understand commands related to procedure and function

Requirements:
Software Requirements: Maria DB, Fedora 20, MYSQL
Hardware Requirements: CPU: Intel Core or Xeon 3GHz (or Dual Core 2GHz) or equal AMD,
Cores: Single (Dual/Quad Core is recommended), RAM: 4 GB (6 GB recommended)

Theory:
Procedures and Functions are the subprograms which can be created and saved in the database as
database objects. They can be called or referred inside the other blocks also.
Parameter:
The parameter is variable or placeholder of any valid PL/SQL data-type through which the PL/SQL
subprogram exchange the values with the main code. This parameter allows to give input to the
subprograms and to extract from these subprograms.

 These parameters should be defined along with the subprograms at the time of creation.
 These parameters are included n the calling statement of these subprograms to interact the
values with the subprograms.
 The datatype of the parameter in the subprogram and the calling statement should be same.
 The size of the datatype should not mention at the time of parameter declaration, as the size is
dynamic for this type.

Based on their purpose parameters are classified as


1. IN Parameter
2. OUT Parameter
3. IN OUT Parameter
IN Parameter:
 This parameter is used for giving input to the subprograms.
 It is a read-only variable inside the subprograms. Their values cannot be changed inside the
subprogram.
 In the calling statement, these parameters can be a variable or a literal value or an expression,
for example, it could be the arithmetic expression like '5*8' or 'a/b' where 'a' and 'b' are
variables.
 By default, the parameters are of IN type.

Department of Computer Engineering 50


Database Management Systems Lab T.E (Computer Engineering)

OUT Parameter:
 This parameter is used for getting output from the subprograms.
 It is a read-write variable inside the subprograms. Their values can be changed inside the
subprograms.
 In the calling statement, these parameters should always be a variable to hold the value from the
current subprograms.

IN OUT Parameter:
 This parameter is used for both giving input and for getting output from the subprograms.
 It is a read-write variable inside the subprograms. Their values can be changed inside the
subprograms.
 In the calling statement, these parameters should always be a variable to hold the value from the
subprograms.

These parameter types should be mentioned at the time of creating the subprograms.

RETURN
RETURN is the keyword that instructs the compiler to switch the control from the subprogram to the
calling statement. In subprogram RETURN simply means that the control needs to exit from the
subprogram. Once the controller finds RETURN keyword in the subprogram, the code after this will be
skipped.
Normally, parent or main block will call the subprograms, and then the control will shift from
those parent blocks to the called subprograms. RETURN in the subprogram will return the control back
to their parent block. In the case of functions RETURN statement also returns the value. The datatype
of this value is always mentioned at the time of function declaration. The datatype can be of any valid
PL/SQL data type.

Procedure in PL/SQL
A Procedure is a subprogram unit that consists of a group of PL/SQL statements. Each procedure in
Oracle has its own unique name by which it can be referred. This subprogram unit is stored as a
database object. Below are the characteristics of this subprogram unit.
 Procedures are standalone blocks of a program that can be stored in the database.
 Call to these procedures can be made by referring to their name, to execute the PL/SQL
statements.
 It is mainly used to execute a process in PL/SQL.
 It can have nested blocks, or it can be defined and nested inside the other blocks or packages.
 It contains declaration part (optional), execution part, exception handling part (optional).
 The values can be passed into the procedure or fetched from the procedure through parameters.
 These parameters should be included in the calling statement.
 Procedure can have a RETURN statement to return the control to the calling block, but it cannot
return any values through the RETURN statement.
 Procedures cannot be called directly from SELECT statements. They can be called from another
block or through EXEC keyword.

Department of Computer Engineering 51


Database Management Systems Lab T.E (Computer Engineering)

Syntax:
CREATE OR REPLACE PROCEDURE
<procedure_name>
(
<parameter IN/OUT <data type>
..
.
)
[ IS | AS ]
<Declaration part>
BEGIN
<Execution part>
EXCEPTION
<Exception handling part>
END;

 CREATE PROCEDURE instructs the compiler to create new procedure. Keyword 'OR
REPLACE' instructs the compile to replace the existing procedure (if any) with the current one.
 Procedure name should be unique.
 Keyword 'IS' will be used, when the procedure is nested into some other blocks. If the
procedure is standalone then 'AS' will be used. Other than this coding standard, both have the
same meaning.

Procedures: Example
The below example creates a procedure ‘employer_details’ which gives the details of the employee.

1> CREATE OR REPLACE PROCEDURE employer_details


2> IS
3> CURSOR emp_cur IS
4> SELECT first_name, last_name, salary FROM emp_tbl;
5> emp_rec emp_cur%rowtype;
6> BEGIN
7> FOR emp_rec in sales_cur
8> LOOP
9> dbms_output.put_line(emp_cur.first_name || ' ' ||emp_cur.last_name
10> || ' ' ||emp_cur.salary);
11> END LOOP;
12>END;
13> /

Function:
A function is a standalone PL/SQL subprogram. Like PL/SQL procedure, functions have a unique
name by which it can be referred. These are stored as PL/SQL database objects. Below are some of the
characteristics of functions.

 Functions are a standalone block that is mainly used for calculation purpose.
 Function use RETURN keyword to return the value, and the datatype of this is defined at the
time of creation.
 A Function should either return a value or raise the exception, i.e. return is mandatory in
functions.

Department of Computer Engineering 52


Database Management Systems Lab T.E (Computer Engineering)

 Function with no DML statements can be directly called in SELECT query whereas the
function with DML operation can only be called from other PL/SQL blocks.
 It can have nested blocks, or it can be defined and nested inside the other blocks or packages.
 It contains declaration part (optional), execution part, exception handling part (optional).
 The values can be passed into the function or fetched from the procedure through the
parameters.
 These parameters should be included in the calling statement.
 Function can also return the value through OUT parameters other than using RETURN.
 Since it will always return the value, in calling statement it always accompanies with
assignment operator to populate the variables.

 CREATE FUNCTION instructs the compiler to create a new function. Keyword 'OR
REPLACE' instructs the compiler to replace the existing function (if any) with the current one.
 The Function name should be unique.
 RETURN datatype should be mentioned.
 Keyword 'IS' will be used, when the procedure is nested into some other blocks. If the
procedure is standalone then 'AS' will be used. Other than this coding standard, both have the
same meaning.

Function: Example
Let’s create a frunction called ''employer_details_func' similar to the one created in stored proc
1> CREATE OR REPLACE FUNCTION employer_details_func
2> RETURN VARCHAR(20);
3> IS
5> emp_name VARCHAR(20);
6> BEGIN
7> SELECT first_name INTO emp_name
8> FROM emp_tbl WHERE empID = '100';
9> RETURN emp_name;
10> END;
11> /

Similarities between Procedure and Function


 Both can be called from other PL/SQL blocks.

Department of Computer Engineering 53


Database Management Systems Lab T.E (Computer Engineering)

 If the exception raised in the subprogram is not handled in the subprogram exception handling
section, then it will propagate to the calling block.
 Both can have as many parameters as required.
 Both are treated as database objects in PL/SQL.

Procedure Vs. Function: Key Differences

Procedure Function

 Used mainly to a execute certain  Used mainly to perform some calculation


process

 Cannot call in SELECT statement  A Function that contains no DML statements


can be called in SELECT statement

 Use OUT parameter to return the  Use RETURN to return the value
value

 It is not mandatory to return the  It is mandatory to return the value


value

 RETURN will simply exit the  RETURN will exit the control from
control from subprogram. subprogram and also returns the value

 Return datatype will not be specified  Return datatype is mandatory at the time of
at the time of creation creation

Program:
[sinhgad@localhost ~]$ su
Password:
[root@localhost sinhgad]# mysql
Welcome to the MariaDB monitor. Commands end with ; or \g.
Your MariaDB connection id is 4
Server version: 5.5.43-MariaDB MariaDB Server
Copyright (c) 2000, 2015, Oracle, MariaDB Corporation Ab and others.
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

MariaDB [(none)]> use stud;


Database changed

MariaDB [stud]> create table stud_marks(rollno int(2),name varchar(12),total_marks int(12));


Query OK, 0 rows affected (0.06 sec)

MariaDB [stud]> insert into stud_marks values(1,"Ravi",933),(2,"sagar",450),(3,"sarita",1300),(4,"avi",250),(5,"raj",675);


Query OK, 5 rows affected (0.02 sec)
Records: 5 Duplicates: 0 Warnings: 0

Department of Computer Engineering 54


Database Management Systems Lab T.E (Computer Engineering)

MariaDB [stud]> select * from stud_marks;


+--------+--------+-------------+
| rollno | name | total_marks |
+--------+--------+-------------+
| 1 | Ravi | 933 |
| 2 | sagar | 450 |
| 3 | sarita | 1300 |
| 4 | avi | 250 |
| 5 | raj | 675 |
+--------+--------+-------------+
5 rows in set (0.00 sec)

MariaDB [stud]> create table new_stud_marks(roll_no int(2),name char(10),grade char(10));


Query OK, 0 rows affected (0.04 sec)

MariaDB [stud]> delimiter //


MariaDB [stud]> CREATE PROCEDURE grade1()
-> BEGIN
-> DECLARE rolln INT;
-> DECLARE stu_name CHAR(50);
-> DECLARE marks INT;
-> DECLARE done INT DEFAULT FALSE;
-> DECLARE cur1 CURSOR FOR SELECT rollno,name,total_marks FROM stud_marks;
-> DECLARE CONTINUE HANDLER FOR NOT FOUND SET done=TRUE;
-> OPEN cur1;
-> read_loop:LOOP
-> FETCH cur1 INTO rolln,stu_name,marks;
-> IF done THEN
-> LEAVE read_loop;
-> END IF;
-> IF(marks>=990 AND marks<=1500)THEN
-> INSERT INTO new_stud_marks values(rolln,stu_name,'DISTINCTION');
-> ELSEIF(marks>=900 AND marks<=989)THEN
-> INSERT INTO new_stud_marks values(rolln,stu_name,'FIRST CLASS');
-> ELSEIF(marks>=825 AND marks<=899)THEN
-> INSERT INTO new_stud_marks values(rolln,stu_name,'SECOND CLASS');
-> ELSE
-> INSERT INTO new_stud_marks values(rolln,stu_name,'FAIL');
-> END IF;
-> END LOOP;
-> CLOSE cur1;
-> END //
Query OK, 0 rows affected (0.00 sec)

MariaDB [stud]> delimiter ;


MariaDB [stud]> describe stud_marks;
+-------------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------------+-------------+------+-----+---------+-------+
| rollno | int(2) | YES | | NULL | |

Department of Computer Engineering 55


Database Management Systems Lab T.E (Computer Engineering)

| name | varchar(12) | YES | | NULL | |


| total_marks | int(12) | YES | | NULL | |
+-------------+-------------+------+-----+---------+-------+
3 rows in set (0.01 sec)

MariaDB [stud]> select * from stud_marks;


+--------+--------+-------------+
| rollno | name | total_marks |
+--------+--------+-------------+
| 1 | Ravi | 933 |
| 2 | sagar | 450 |
| 3 | sarita | 1300 |
| 4 | avi | 250 |
| 5 | raj | 675 |
+--------+--------+-------------+
5 rows in set (0.00 sec)

MariaDB [stud]> describe new_stud_marks;


+---------+----------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+---------+----------+------+-----+---------+-------+
| roll_no | int(2) | YES | | NULL | |
| name | char(10) | YES | | NULL | |
| grade | char(10) | YES | | NULL | |
+---------+----------+------+-----+---------+-------+
3 rows in set (0.00 sec)

MariaDB [stud]> select * from new_stud_marks;


Empty set (0.00 sec)

MariaDB [stud]> call grade1;


Query OK, 0 rows affected, 0 warning (0.05 sec)

MariaDB [stud]> select * from new_stud_marks;


+---------+--------+------------+
| roll_no | name | grade |
+---------+--------+------------+
| 1 | Ravi | FIRST CLAS |
| 2 | sagar | FAIL |
| 3 | sarita | DISTINCTIO |
| 4 | avi | FAIL |
| 5 | raj | FAIL |
+---------+--------+------------+
5 rows in set (0.00 sec)

Conclusion: Performed implementation of procedures and functions in MYSQL successfully.

Department of Computer Engineering 56


Database Management Systems Lab T.E (Computer Engineering)

ASSIGNMENT NO.: 8

Title: Database Trigger (All Types: Row level and Statement level triggers, Before and After
Triggers). Write a database trigger on Library table. The System should keep track of the records that
are being updated or deleted. The old value of updated or deleted records should be added in
Library_Audit table.
Objectives: To understand the concept of MySQL database trigger.

Requirements:
Software Requirements: Maria DB, Fedora 20, MYSQL
Hardware Requirements: CPU: Intel Core or Xeon 3GHz (or Dual Core 2GHz) or equal AMD,
Cores: Single (Dual/Quad Core is recommended), RAM: 4 GB (6 GB recommended)

Theory:

1. Introduction to MySQL Trigger:


A trigger is a named database object that is associated with a table, and that activates when a
particular event occurs for the table. Some uses for triggers are to perform checks of values to be
inserted into a table or to perform calculations on values involved in an update.
A trigger is a set of actions that are run automatically when a specified change operation (SQL
INSERT, UPDATE, or DELETE statement) is performed on a specified table. A trigger is defined to
activate when a statement inserts, updates, or deletes rows in the associated table. These row operations
are trigger events. For example, rows can be inserted by INSERT or LOAD DATA statements, and an
insert trigger activates for each inserted row. A trigger can be set to activate either before or after the
trigger event. For example, we can have a trigger activate before each row that is inserted into a table
or after each row that is updated.
Triggers are useful for tasks such as enforcing business rules, validating input data, and keeping
an audit trail.

2. Types of Triggers:
There are two types of triggers based on which level it is triggered.
1) Row level Trigger: An event is triggered for each row updated, inserted or deleted.
2) Statement level Trigger: An event is triggered for each SQL statement executed.

3. Trigger Execution Hierarchy:


The following hierarchy is followed when a trigger is fired.
1) BEFORE statement trigger fires first.
2) Next BEFORE row level trigger fires, once for each row affected.
3) Then AFTER row level trigger fires once for each affected row. This events will alternates between
BEFORE and AFTER row level triggers.
4) Finally the AFTER statement level trigger fires.

4. Syntax for Creating a Trigger


CREATE [OR REPLACE ] TRIGGER trigger_name
{BEFORE | AFTER | INSTEAD OF }
{INSERT [OR] | UPDATE [OR] | DELETE}

Department of Computer Engineering 57


Database Management Systems Lab T.E (Computer Engineering)

[OF col_name]
ON table_name
[REFERENCING OLD AS o NEW AS n]
[FOR EACH ROW]
WHEN (condition)
BEGIN
--- sql statements
END;

Arguments or Parameters:

 CREATE [OR REPLACE ] TRIGGER trigger_name - This clause creates a trigger with the
given name or overwrites an existing trigger with the same name.
 {BEFORE | AFTER | INSTEAD OF } - This clause indicates at what time should the trigger get
fired. i.e for example: before or after updating a table. INSTEAD OF is used to create a trigger
on a view. before and after cannot be used to create a trigger on a view.
 {INSERT [OR] | UPDATE [OR] | DELETE} - This clause determines the triggering event.
More than one triggering events can be used together separated by OR keyword. The trigger
gets fired at all the specified triggering event.
 [OF col_name] - This clause is used with update triggers. This clause is used when you want to
trigger an event only when a specific column is updated.
 CREATE [OR REPLACE ] TRIGGER trigger_name - This clause creates a trigger with the
given name or overwrites an existing trigger with the same name.
 [ON table_name] - This clause identifies the name of the table or view to which the trigger is
associated.
 [REFERENCING OLD AS o NEW AS n] - This clause is used to reference the old and new
values of the data being changed. By default, you reference the values as :old.column_name or
:new.column_name. The reference names can also be changed from old (or new) to any other
user-defined name. You cannot reference old values when inserting a record, or new values
when deleting a record, because they do not exist.
 [FOR EACH ROW] - This clause is used to determine whether a trigger must fire when each
row gets affected ( i.e. a Row Level Trigger) or just once when the entire sql statement is
executed(i.e.statement level Trigger).
 WHEN (condition) - This clause is valid only for row level triggers. The trigger is fired only for
rows that satisfy the condition specified.

5. Trigger Examples:
Example 1:
The price of a product changes constantly. It is important to maintain the history of the prices of the
products.
A trigger can be created to update the 'product_price_history' table when the price of the product is
updated in the 'product' table.
1) Create the 'product' table and 'product_price_history' table:
CREATE TABLE product_price_history
(product_id number(5),
product_name varchar2(32),
supplier_name varchar2(32),
unit_price number(7,2) );
Department of Computer Engineering 58
Database Management Systems Lab T.E (Computer Engineering)

CREATE TABLE product


(product_id number(5),
product_name varchar2(32),
supplier_name varchar2(32),
unit_price number(7,2) );

2) Create the price_history_trigger and execute it:


CREATE or REPLACE TRIGGER price_history_trigger
BEFORE UPDATE OF unit_price
ON product
FOR EACH ROW
BEGIN
INSERT INTO product_price_history
VALUES
(:old.product_id,
:old.product_name,
:old.supplier_name,
:old.unit_price);
END;
/

3) Update the price of a product:


UPDATE PRODUCT SET unit_price = 800 WHERE product_id = 100
Once the above update query is executed, the trigger fires and updates the 'product_price_history' table.

4)If we ROLLBACK the transaction before committing to the database, the data inserted to the table is
also rolled back.

Example 2:
In the following example, we have two tables: emp_details and log_emp_details. To insert some
information into log_ emp_details table (which have three fields employee id and salary and edttime)
every time, when an INSERT happen into emp_details table we have used the following trigger :
DELIMITER
$$
USE `hr`
$$
CREATE
DEFINER=`root`@`127.0.0.1`
TRIGGER `hr`.`emp_details_AINS`
AFTER INSERT ON `hr`.`emp_details`
FOR EACH ROW
-- Edit trigger body code below this line. Do not edit lines above this one
BEGIN
INSERT INTO log_emp_details
VALUES(NEW.employee_id, NEW.salary, NOW());
END$$

Records of the table (on some columns) : emp_details


Department of Computer Engineering 59
Database Management Systems Lab T.E (Computer Engineering)

mysql> SELECT EMPLOYEE_ID, FIRST_NAME, LAST_NAME, JOB_ID, SALARY,


COMMISSION_PCT FROM emp_details;
+-------------+------------+-----------+---------+----------+----------------+
| EMPLOYEE_ID | FIRST_NAME | LAST_NAME | JOB_ID | SALARY | COMMISSION_PCT |
+-------------+------------+-----------+---------+----------+----------------+
| 100 | Steven | King | AD_PRES | 24000.00 | 0.10 |
| 101 | Neena | Kochhar | AD_VP | 17000.00 | 0.50 |
| 102 | Lex | De Haan | AD_VP | 17000.00 | 0.50 |
| 103 | Alexander | Hunold | IT_PROG | 9000.00 | 0.25 |
| 104 | Bruce | Ernst | IT_PROG | 6000.00 | 0.25 |
| 105 | David | Austin | IT_PROG | 4800.00 | 0.25 |
+-------------+------------+-----------+---------+----------+----------------+

Records of the table (all columns) : log_emp_details


mysql> SELECT * FROM log_emp_details;
+-------------+----------+---------------------+
| emp_details | SALARY | EDTTIME |
+-------------+----------+---------------------+
| 100 | 24000.00 | 2011-01-15 00:00:00 |
| 101 | 17000.00 | 2010-01-12 00:00:00 |
| 102 | 17000.00 | 2010-09-22 00:00:00 |
| 103 | 9000.00 | 2011-06-21 00:00:00 |
| 104 | 6000.00 | 2012-07-05 00:00:00 |
| 105 | 4800.00 | 2011-06-21 00:00:00 |
+-------------+----------+---------------------+

Now insert one record in emp_details table see the records both in emp_details and log_emp_details
tables :
mysql> INSERT INTO emp_details VALUES(236, 'RABI', 'CHANDRA', 'RABI','590.423.45700',
'2013-01-12', 'AD_VP', 15000, .5);

mysql> SELECT EMPLOYEE_ID, FIRST_NAME, LAST_NAME, JOB_ID, SALARY,


COMMISSION_PCT FROM emp_details;

+-------------+------------+-----------+---------+----------+----------------+
| EMPLOYEE_ID | FIRST_NAME | LAST_NAME | JOB_ID | SALARY | COMMISSION_PCT |
+-------------+------------+-----------+---------+----------+----------------+
| 100 | Steven | King | AD_PRES | 24000.00 | 0.10 |
| 101 | Neena | Kochhar | AD_VP | 17000.00 | 0.50 |
| 102 | Lex | De Haan | AD_VP | 17000.00 | 0.50 |
| 103 | Alexander | Hunold | IT_PROG | 9000.00 | 0.25 |
| 104 | Bruce | Ernst | IT_PROG | 6000.00 | 0.25 |
| 105 | David | Austin | IT_PROG | 4800.00 | 0.25 |
| 236 | RABI | CHANDRA | AD_VP | 15000.00 | 0.50 |
+-------------+------------+-----------+---------+----------+----------------+

mysql> SELECT * FROM log_emp_details;

Department of Computer Engineering 60


Database Management Systems Lab T.E (Computer Engineering)

+-------------+----------+---------------------+
| emp_details | SALARY | EDTTIME |
+-------------+----------+---------------------+
| 100 | 24000.00 | 2011-01-15 00:00:00 |
| 101 | 17000.00 | 2010-01-12 00:00:00 |
| 102 | 17000.00 | 2010-09-22 00:00:00 |
| 103 | 9000.00 | 2011-06-21 00:00:00 |
| 104 | 6000.00 | 2012-07-05 00:00:00 |
| 105 | 4800.00 | 2011-06-21 00:00:00 |
| 236 | 15000.00 | 2013-07-15 16:52:24 |
+-------------+----------+---------------------+

Example 3:
In the following example, before insert a new record in emp_details table, a trigger check the column
value of FIRST_NAME, LAST_NAME, JOB_ID and
- If there are any space(s) before or after the FIRST_NAME, LAST_NAME, TRIM() function will
remove those.
- The value of the JOB_ID will be converted to upper cases by UPPER() function.

Here is the trigger code:


USE `hr`;
DELIMITER
$$
CREATE TRIGGER `emp_details_BINS`
BEFORE INSERT
ON emp_details FOR EACH ROW
-- Edit trigger body code below this line. Do not edit lines above this one
BEGIN
SET NEW.FIRST_NAME = TRIM(NEW.FIRST_NAME);
SET NEW.LAST_NAME = TRIM(NEW.LAST_NAME);
SET NEW.JOB_ID = UPPER(NEW.JOB_ID);END;
$$
Now insert a row into emp_details table (check the FIRST_NAME, LAST_NAME, JOB_ID columns)
:
mysql> INSERT INTO emp_details VALUES (334, ' Ana ', ' King', 'ANA', '690.432.45701', '2013-02-
05', 'it_prog', 17000, .50);

Now list the following fields of emp_details :


mysql> SELECT EMPLOYEE_ID, FIRST_NAME, LAST_NAME, JOB_ID, SALARY,
COMMISSION_PCT FROM emp_details;
+-------------+------------+-----------+---------+----------+----------------+
| EMPLOYEE_ID | FIRST_NAME | LAST_NAME | JOB_ID | SALARY | COMMISSION_PCT |
+-------------+------------+-----------+---------+----------+----------------+
| 100 | Steven | King | AD_PRES | 24000.00 | 0.10 |
| 101 | Neena | Kochhar | AD_VP | 17000.00 | 0.50 |
| 102 | Lex | De Haan | AD_VP | 17000.00 | 0.50 |
| 103 | Alexander | Hunold | IT_PROG | 9000.00 | 0.25 |
| 104 | Bruce | Ernst | IT_PROG | 6000.00 | 0.25 |
Department of Computer Engineering 61
Database Management Systems Lab T.E (Computer Engineering)

| 105 | David | Austin | IT_PROG | 4800.00 | 0.25 |


| 236 | RABI | CHANDRA | AD_VP | 15000.00 | 0.50 |
| 334 | Ana | King | IT_PROG | 17000.00 | 0.50 |
+-------------+------------+-----------+---------+----------+----------------+

See the last row :


FIRST_NAME - > ' Ana ' has changed to 'Ana'
LAST_NAME - > ' King' has changed to 'King'
JOB_ID - > ' it_prog' has changed to 'IT_PROG'

6. Delete a MySQL trigger


Once a trigger has been created in MySQL, it can be deleted or dropped using the DROP TRIGGER
statement.
Syntax:
DROP TRIGGER trigger_name;
Parameters or Arguments
trigger_name: The name of the trigger that you wish to drop.

Example:
DROP TRIGGER orders_before_insert;
This example uses the ALTER TRIGGER statement to drop the trigger called orders_before_insert.

Program:
[sinhgad@localhost ~]$ su
Password:
[root@localhost sinhgad]# mysql
Welcome to the MariaDB monitor. Commands end with ; or \g.
Your MariaDB connection id is 5
Server version: 5.5.43-MariaDB MariaDB Server

Copyright (c) 2000, 2015, Oracle, MariaDB Corporation Ab and others.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

MariaDB [(none)]> create database assign8;


Query OK, 1 row affected (0.02 sec)

MariaDB [(none)]> use assign8;


Database changed

MariaDB [assign8]> create table library(accession int,title varchar(50),author varchar(30),publisher varchar(50));


Query OK, 0 rows affected (0.06 sec)

MariaDB [assign8]> create table library_audit(accession int,title varchar(50),author varchar(30),publisher


varchar(50),operation varchar(10));
Query OK, 0 rows affected (0.04 sec)

MariaDB [assign8]> create trigger update_lib after update on library for each row insert into
library_audit(accession,title,author,publisher,operation) values(old.accession,old.title,old.author,old.publisher,'UPDATE');
Query OK, 0 rows affected (0.07 sec)

Department of Computer Engineering 62


Database Management Systems Lab T.E (Computer Engineering)

MariaDB [assign8]> create trigger delete_lib after delete on library for each row insert into library_audit(accession,
title,author,publisher,operation) values(old.accession,old.title,old.author,old.publisher,'DELETE');
Query OK, 0 rows affected (0.09 sec)
MariaDB [assign8]> insert into library(accession,title,author,publisher) values(101,'OPERATING
SYSTEM','KORTH','MCG');
Query OK, 1 row affected (0.01 sec)
MariaDB [assign8]> insert into library(accession,title,author,publisher) values(102,'PROGRAMMING IN
C','BALAGURUSWAMY','BPB');
Query OK, 1 row affected (0.01 sec)
MariaDB [assign8]> insert into library(accession,title,author,publisher) values(103,'HOW TO LEARN
C','KANETKAR','TECHMAX');
Query OK, 1 row affected (0.01 sec)

MariaDB [assign8]> select * from library;


+-----------+------------------+---------------+-----------+
| accession | title | author | publisher |
+-----------+------------------+---------------+-----------+
| 101 | OPERATING SYSTEM | KORTH | MCG |
| 102 | PROGRAMMING IN C | BALAGURUSWAMY | BPB |
| 103 | HOW TO LEARN C | KANETKAR | TECHMAX |
+-----------+------------------+---------------+-----------+
3 rows in set (0.00 sec)

MariaDB [assign8]> select * from library_audit;


Empty set (0.00 sec)
MariaDB [assign8]> update library set publisher='MC GRAW HILL' where accession=101;
Query OK, 1 row affected (0.03 sec)

MariaDB [assign8]> select * from library_audit;


+-----------+------------------+--------+-----------+-----------+
| accession | title | author | publisher | operation |
+-----------+------------------+--------+-----------+-----------+
| 101 | OPERATING SYSTEM | KORTH | MCG | UPDATE |
+-----------+------------------+--------+-----------+-----------+
1 row in set (0.00 sec)

MariaDB [assign8]> delete from library where accession=103;


Query OK, 1 row affected (0.02 sec)
MariaDB [assign8]> select * from library_audit;
+-----------+------------------+----------+-----------+-----------+
| accession | title | author | publisher | operation |
+-----------+------------------+----------+-----------+-----------+
| 101 | OPERATING SYSTEM | KORTH | MCG | UPDATE |
| 103 | HOW TO LEARN C | KANETKAR | TECHMAX | DELETE |
+-----------+------------------+----------+-----------+-----------+
2 rows in set (0.00 sec)

MariaDB [assign8]> select * from library;


+-----------+------------------+---------------+--------------+
| accession | title | author | publisher |
+-----------+------------------+---------------+--------------+
| 101 | OPERATING SYSTEM | KORTH | MC GRAW HILL |
| 102 | PROGRAMMING IN C | BALAGURUSWAMY | BPB |
+-----------+------------------+---------------+--------------+
2 rows in set (0.00 sec)

Conclusion: Studied and implemented MySQL Trigger.

Department of Computer Engineering 63


Database Management Systems Lab T.E (Computer Engineering)

GROUP B

Department of Computer Engineering 64


Database Management Systems Lab T.E (Computer Engineering)

ASSIGNMENT NO.: 1

Title: Study of Open Source NOSQL Database: MongoDB (Installation, Basic CRUD operations,
Execution)

Objective: To study and learn all basic operations of MongoDB.

Requirements:
Software Requirements:Fedora 20, MYSQL, MongoDB, Java/Python
Hardware Requirements: CPU: Intel Core or Xeon 3GHz (or Dual Core 2GHz) or equal AMD,
Cores: Single (Dual/Quad Core is recommended), RAM: 4 GB (6 GB recommended)

Theory:

Introduction to MongoDB:

 MongoDB is a document database with the scalability and flexibility that you want with the
querying and indexing that you need
 MongoDB stores data in flexible, JSON-like documents, meaning fields can vary from
document to document and data structure can be changed over time
 The document model maps to the objects in your application code, making data easy to work
with
 Ad hoc queries, indexing, and real time aggregation provide powerful ways to access and
analyze your data
 MongoDB is a distributed database at its core, so high availability, horizontal scaling, and
geographic distribution are built in and easy to use
 MongoDB is free and open-source, published under the GNU Affero General Public License.

MongoDB CRUD Operations:


CRUD operations are create, read, update, and delete documents.

1) Create Operations
Create or insert operations add new documents to a collection. If the collection does not currently exist,
insert operations will create the collection.
MongoDB provides the following methods to insert documents into a collection:
 db.collection.insertOne()
 db.collection.insertMany()

In MongoDB, insert operations target a single collection. All write operations in MongoDB
are atomic on the level of a single document.

Example 1:
The following example inserts a new document into the inventory collection. If the document does not
specify an _id field, MongoDB adds the _id field with an ObjectId value to the new document.

db.inventory.insertOne(
{item: "canvas", qty: 100, tags: ["cotton"], size: { h: 28, w: 35.5, uom: "cm" } })

Department of Computer Engineering 65


Database Management Systems Lab T.E (Computer Engineering)

Example 2:
The following example inserts three new documents into the inventory collection. If the documents do
not specify an _id field, MongoDB adds the _id field with an ObjectId value to each document.
db.inventory.insertMany([
{item: "journal", qty: 25, tags: ["blank", "red"], size: { h: 14, w: 21, uom: "cm" } },
{item: "mat", qty: 85, tags: ["gray"], size: { h: 27.9, w: 35.5, uom: "cm" } },
{item: "mousepad", qty: 25, tags: ["gel", "blue"], size: { h: 19, w: 22.85, uom: "cm" } }
])

2) Read Operations:
Read operations retrieve documents from a collection; i.e. queries a collection for documents.
MongoDB provides the following methods to read documents from a collection:
Syntax:
db.collection.find()
Example:
The following example selects from the inventory collection all documents where
the status equals "D":
db.inventory.find( { status: "D" } )

3) Update Operation:
Update operations modify existing documents in a collection. MongoDB provides the following
methods to update documents of a collection:
 db.collection.updateOne()
 db.collection.updateMany()
 db.collection.replaceOne()
In MongoDB, update operations target a single collection. All write operations in MongoDB
are atomic on the level of a single document.
Example:
db.users.update({name:"John Doe"}, {age: 28})

4) Delete Operations:
Delete operations remove documents from a collection. The remove() method is used to delete data or
sets of data from your database:
Example:
db.users.remove({name: "John Doe"})

Installation steps of MongoDB:

1) Extract the .rar file into any directory of computer.


2) Go to directory & select mongo db file.
3) Go upto the bin & select its properties and take its path.(e.g. path/home/sinhgad/mongodb-
linux-x86_64-3.0.2).
4) Open Terminal.
5) Login to super user, write the path of bin.(e.g cd mongodb-linux-x86_64-3.0.2/)
6) If the path is correct then there is no error & it will display: [root@localhost Documents]# cd
mongodb-linux-x86_64-3.0.2/bin/
7) Then write ./mongod
8) Then open a new Tab and write ./mongo and start coding for MongoDB.
Department of Computer Engineering 66
Database Management Systems Lab T.E (Computer Engineering)

Program:
[sinhgad@localhost ~]$ su
Password:

[root@localhost sinhgad]# cd Documents

[root@localhost Documents]# ls
abhi.asm Dining.java mongo-java-driver-2.12.2.jar
abhishek EL-III Ass_A1 overlap
abhishek.asm jdk-8u161-nb-8_2-linux-x64.sh overlap.asm~
abhishek.o Link to sachin.cpp overlap.o
add.asm mongo overlapp.asm
a.out mongodb-linux-x86_64-2.6.3 S151024282.cpp
cloudsim-3.0.2 mongodb-linux-x86_64-3.0.2 sachin.cpp~
cloudsim-3.0.2.jar mongo-java-driver-2.12.2 vishal
[root@localhost Documents]# cd mongodb-linux-x86_64-3.0.2/bin/

[root@localhost bin]# ./mongod


2018-07-13T14:36:58.573+0530 W - [initandlisten] Detected unclean shutdown - /data/db/mongod.lock is not empty.
2018-07-13T14:40:32.219+0530 I STORAGE [FileAllocator] done allocating datafile /data/db/office.0, size: 64MB, took
0.023 secs
2018-07-13T14:40:32.342+0530 I COMMAND [conn1] command office.$cmd command: create { create: "Employee" }
keyUpdates:0 writeConflicts:0 numYields:0 reslen:37 locks:{ Global: { acquireCount: { w: 1 } }, MMAPV1Journal: {
acquireCount: { w: 6 }, acquireWaitCount: { w: 1 }, timeAcquiringMicros: { w: 24 } }, Database: { acquireCount: { W: 1 }
}, Metadata: { acquireCount: { W: 4 } } } 466ms

OPEN A NEW TAB IN TERMINAL

[sinhgad@localhost bin]$ ./mongo


MongoDB shell version: 3.0.2
connecting to: test
Server has startup warnings:
2018-07-13T14:37:10.838+0530 I CONTROL [initandlisten] ** WARNING: You are running this process as the root user,
which is not recommended.
2018-07-13T14:37:10.863+0530 I CONTROL [initandlisten] ** WARNING: /sys/kernel/mm/transparent_hugepage/defrag
is 'always'.

> use office;


switched to db office

> db.createCollection("Employee");
{ "ok" : 1 }
>
db.Employee.insert([{"empID":21,"Name":"Tejal","Salary":200},{"empID":22,"Name":"Harsh","Salary":180},{"empID":2
4,"Name":"Nayan","Salary":230},{"empID":38,"Name":"Rutuja","Salary":210}]);
BulkWriteResult({
"writeErrors" : [ ],
"writeConcernErrors" : [ ],
"nInserted" : 4,
"nUpserted" : 0,
"nMatched" : 0,
"nModified" : 0,
"nRemoved" : 0,
"upserted" : [ ]
})

Department of Computer Engineering 67


Database Management Systems Lab T.E (Computer Engineering)

> db.Employee.find().pretty();
{
"_id" : ObjectId("5b486d9703c720f873a7839e"),
"empID" : 21,
"Name" : "Tejal",
"Salary" : 200
}
{
"_id" : ObjectId("5b486d9703c720f873a7839f"),
"empID" : 22,
"Name" : "Harsh",
"Salary" : 180
}
{
"_id" : ObjectId("5b486d9703c720f873a783a0"),
"empID" : 24,
"Name" : "Nayan",
"Salary" : 230
}
{
"_id" : ObjectId("5b486d9703c720f873a783a1"),

"empID" : 38,
"Name" : "Rutuja",
"Salary" : 210
}
> db.Employee.update({"Name":"Rutuja"},{$set:{"Salary":225}});
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.Employee.find().pretty();
{
"_id" : ObjectId("5b486d9703c720f873a7839e"),
"empID" : 21,
"Name" : "Tejal",
"Salary" : 200
}
{
"_id" : ObjectId("5b486d9703c720f873a7839f"),
"empID" : 22,
"Name" : "Harsh",
"Salary" : 180
}
{
"_id" : ObjectId("5b486d9703c720f873a783a0"),
"empID" : 24,
"Name" : "Nayan",
"Salary" : 230
}
{
"_id" : ObjectId("5b486d9703c720f873a783a1"),
"empID" : 38,
"Name" : "Rutuja",
"Salary" : 225
}
> db.Employee.remove({"Name":"Harsh"})
WriteResult({ "nRemoved" : 1 })
> db.Employee.find().pretty();
{

Department of Computer Engineering 68


Database Management Systems Lab T.E (Computer Engineering)

"_id" : ObjectId("5b486d9703c720f873a7839e"),
"empID" : 21,
"Name" : "Tejal",
"Salary" : 200
}
{
"_id" : ObjectId("5b486d9703c720f873a783a0"),
"empID" : 24,
"Name" : "Nayan",
"Salary" : 230
}
{
"_id" : ObjectId("5b486d9703c720f873a783a1"),
"empID" : 38,

"Name" : "Rutuja",
"Salary" : 225
}

Conclusion: Successfully installed and implemented CRUD operation using MongoDB.

Department of Computer Engineering 69


Database Management Systems Lab T.E (Computer Engineering)

ASSIGNMENT NO.: 2

Title: Design and Develop MongoDB Queries using CRUD operations. (Use CRUD operations, SAVE
method, logical operators).

Objective: To study and learn MongoDB all basic operations as well as SAVE method and logical
operations.

Requirements:
Software Requirements:Fedora 20, MYSQL, MongoDB, Java/Python
Hardware Requirements: CPU: Intel Core or Xeon 3GHz (or Dual Core 2GHz) or equal AMD,
Cores: Single (Dual/Quad Core is recommended), RAM: 4 GB (6 GB recommended)

Theory:
MongoDB

 MongoDB is a document database with the scalability and flexibility that you want with the
querying and indexing that you need
 MongoDB stores data in flexible, JSON-like documents, meaning fields can vary from
document to document and data structure can be changed over time
 The document model maps to the objects in your application code, making data easy to work
with
 Ad hoc queries, indexing, and real time aggregation provide powerful ways to access and
analyze your data
 MongoDB is a distributed database at its core, so high availability, horizontal scaling, and
geographic distribution are built in and easy to use
 MongoDB is free and open-source, published under the GNU Affero General Public License.

MongoDB CRUD Operations:


CRUD operations are create, read, update, and delete documents.

Create Operations
Create or insert operations add new documents to a collection. If the collection does not currently exist,
insert operations will create the collection.
MongoDB provides the following methods to insert documents into a collection:
 db.collection.insertOne()
 db.collection.insertMany()

In MongoDB, insert operations target a single collection. All write operations in MongoDB
are atomic on the level of a single document.

Example 1:
The following example inserts a new document into the inventory collection. If the document does not
specify an _id field, MongoDB adds the _id field with an ObjectId value to the new document.
db.inventory.insertOne(
{item: "canvas", qty: 100, tags: ["cotton"], size: { h: 28, w: 35.5, uom: "cm" } })

Department of Computer Engineering 70


Database Management Systems Lab T.E (Computer Engineering)

Example 2:
The following example inserts three new documents into the inventory collection. If the documents do
not specify an _id field, MongoDB adds the _id field with an ObjectId value to each document.
db.inventory.insertMany([
{ item: "journal", qty: 25, tags: ["blank", "red"], size: { h: 14, w: 21, uom: "cm" } },
{ item: "mat", qty: 85, tags: ["gray"], size: { h: 27.9, w: 35.5, uom: "cm" } },
{ item: "mousepad", qty: 25, tags: ["gel", "blue"], size: { h: 19, w: 22.85, uom: "cm" } }
])

Read Operations:
Read operations retrieves documents from a collection; i.e. queries a collection for documents.
MongoDB provides the following methods to read documents from a collection:
Syntax:
db.collection.find()
Example:
The following example selects from the inventory collection all documents where
the status equals "D":
db.inventory.find( { status: "D" } )

Update Operation:
Update operations modify existing documents in a collection. MongoDB provides the following
methods to update documents of a collection:
 db.collection.updateOne()
 db.collection.updateMany()
 db.collection.replaceOne()
In MongoDB, update operations target a single collection. All write operations in MongoDB
are atomic on the level of a single document.
Example:
db.users.update({name:"John Doe"}, {age: 28})

Delete Operations:
Delete operations remove documents from a collection. The remove() method is used to delete data or
sets of data from your database:

Example:

db.users.remove({name: "John Doe"})

MongoDB SAVE Method:


The save () method replaces the existing document with the new document passed in the save()
method.
Syntax:
The basic syntax of MongoDB save() method is shown below −
>db.COLLECTION_NAME.save({_id:ObjectId(),NEW_DATA})
Example:
Following example will replace the document with the _id '5983548781331adf45ec5'.

Department of Computer Engineering 71


Database Management Systems Lab T.E (Computer Engineering)

>db.mycol.save(
{
"_id" : ObjectId(5983548781331adf45ec7), "title":" New Topic",
"by":"Mongo"
}
)

Logical Operations:
1) AND Operation:
The MongoDB $and operator performs a logical AND operation on an array of two or more
expressions and retrieves the documents which satisfy all the expressions in the array. The $and
operator uses short-circuit evaluation. If the first expression (e.g. <expression1>) evaluates to false,
MongoDB will not evaluate the remaining expressions.
Syntax: { $and: [ { <exp1> }, { <exp2> } , ... , { <expN> } ] }
Example:
db.student.find({$and:[{"gender":"Male"},{"grd_point":{ $gte: 31 }},{"class":"VI"}]}).pretty();

2) OR operation:
The $or operator performs a logical OR operation on an array of two or more <expressions> and selects
the documents that satisfy at least one of the <expressions>.
Syntax:
{ $or: [ { <expression1> }, { <expression2> }, ... , { <expressionN> } ]
Example:
db.inventory.find( { $or: [ { quantity: { $lt: 20 } }, { price: 10 } ] } )

This query will select all documents in the inventory collection where either the quantity field value is
less than 20 or the price field value equals 10.

3) NOT operation:
$not performs a logical NOT operation on the specified <operator-expression> and selects the
documents that do not match the <operator-expression>. This includes documents that do not contain
the field.
Syntax: { field: { $not: { <operator-expression> } } }

Example:
db.inventory.find( { price: { $not: { $gt: 1.99 } } } )
This query will select all documents in the inventory collection where:
 the price field value is less than or equal to 1.99 or
 the price field does not exist

Comparison Operators:
1) $gt
$gt selects those documents where the value of the field is greater than (i.e. >) the specified value.
Syntax: {field: {$gt: value} }
Example:
db.inventory.find( { qty: { $gt: 20 } } )

Department of Computer Engineering 72


Database Management Systems Lab T.E (Computer Engineering)

This query will select all documents in the inventory collection where the qty field value is greater
than 20.

2) $lt
$lt selects the documents where the value of the field is less than (i.e. <) the specified value.
Syntax: {field: {$lt: value} }
Example:
db.inventory.find( { qty: { $lt: 20 } } )
This query will select all documents in the inventory collection where the qty field value is less
than 20.

Program:
[sinhgad@localhost ~]$ su
Password:
[root@localhost sinhgad]# cd Documents
[root@localhost Documents]# ls
5970502.zip eclipse mongodb-linux-x86_64-3.0.2 mysql-connector-java-5.1.46 org report_template_final
tecompsyllabus.pdf
com META-INF mongodb-linux-x86_64-3.0.2.tgz mysql-connector-java-5.1.46.zip pymongo
Sample_PPT_Review1-1.pptx
[root@localhost Documents]# cd mongodb-linux-x86_64-3.0.2/bin/
[root@localhost bin]# ./mongod
---------------------------------------------------------------------------------------------------------------
Open in New Tab
[sinhgad@localhost bin]$ ./mongo
MongoDB shell version: 3.0.2
connecting to: test
Server has startup warnings:
2018-08-07T09:24:36.947+0530 I CONTROL [initandlisten] ** WARNING: You are running this process as the root user,
which is not recommended.
2018-08-07T09:24:36.947+0530 I CONTROL [initandlisten]
2018-08-07T09:24:36.961+0530 I CONTROL [initandlisten]
2018-08-07T09:24:36.961+0530 I CONTROL [initandlisten] ** WARNING:
/sys/kernel/mm/transparent_hugepage/enabled is 'always'.
2018-08-07T09:24:36.961+0530 I CONTROL [initandlisten] ** We suggest setting it to 'never'
2018-08-07T09:24:36.961+0530 I CONTROL [initandlisten]
2018-08-07T09:24:36.961+0530 I CONTROL [initandlisten] ** WARNING: /sys/kernel/mm/transparent_hugepage/defrag
is 'always'.
2018-08-07T09:24:36.961+0530 I CONTROL [initandlisten] ** We suggest setting it to 'never'
2018-08-07T09:24:36.961+0530 I CONTROL [initandlisten]
=======================================================================
> use office;
switched to db office
=======================================================================
> db.createCollection("Employee");
{ "ok" : 0, "errmsg" : "collection already exists", "code" : 48 }
> db.createCollection("Employee1");
{ "ok" : 1 }

>
db.Employee1.insert([{"empID":21,"Name":"John","Salary":200},{"empID":22,"Name":"cloria","Salary":300},{"empID":
23,"Name":"Rachel","Salary":400},{"empID":24,"Name":"Chandler","Salary":500}]);
BulkWriteResult({
"writeErrors" : [ ],
"writeConcernErrors" : [ ],

Department of Computer Engineering 73


Database Management Systems Lab T.E (Computer Engineering)

"nInserted" : 4,
"nUpserted" : 0,
"nMatched" : 0,
"nModified" : 0,
"nRemoved" : 0,
"upserted" : [ ]
})
=======================================================================
> db.Employee1.find().pretty();
{
"_id" : ObjectId("5b691a9835bf2db0d02756a1"),
"empID" : 21,
"Name" : "John",
"Salary" : 200
}
{
"_id" : ObjectId("5b691a9835bf2db0d02756a2"),
"empID" : 22,
"Name" : "cloria",
"Salary" : 300
}
{
"_id" : ObjectId("5b691a9835bf2db0d02756a3"),
"empID" : 23,
"Name" : "Rachel",
"Salary" : 400
}
{
"_id" : ObjectId("5b691a9835bf2db0d02756a4"),
"empID" : 24,
"Name" : "Chandler",
"Salary" : 500
}
=======================================================================
> db.Employee1.update({"Name":"Rachel"},{$set:{"Salary":450}});
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.Employee1.find().pretty();
{
"_id" : ObjectId("5b691a9835bf2db0d02756a1"),
"empID" : 21,
"Name" : "John",
"Salary" : 200
}
{
"_id" : ObjectId("5b691a9835bf2db0d02756a2"),
"empID" : 22,
"Name" : "cloria",
"Salary" : 300
}
{
"_id" : ObjectId("5b691a9835bf2db0d02756a3"),
"empID" : 23,

"Name" : "Rachel",
"Salary" : 450
}
{

Department of Computer Engineering 74


Database Management Systems Lab T.E (Computer Engineering)

"_id" : ObjectId("5b691a9835bf2db0d02756a4"),
"empID" : 24,
"Name" : "Chandler",
"Salary" : 500
}
====================================================================
> db.Employee1.find({"Salary":{$gt:300}});
{ "_id" : ObjectId("5b691a9835bf2db0d02756a3"), "empID" : 23, "Name" : "Rachel", "Salary" : 450 }
{ "_id" : ObjectId("5b691a9835bf2db0d02756a4"), "empID" : 24, "Name" : "Chandler", "Salary" : 500 }
> db.Employee1.find({"Salary":{$gte:300}});
{ "_id" : ObjectId("5b691a9835bf2db0d02756a2"), "empID" : 22, "Name" : "cloria", "Salary" : 300 }
{ "_id" : ObjectId("5b691a9835bf2db0d02756a3"), "empID" : 23, "Name" : "Rachel", "Salary" : 450 }
{ "_id" : ObjectId("5b691a9835bf2db0d02756a4"), "empID" : 24, "Name" : "Chandler", "Salary" : 500 }
> db.Employee1.find({"Salary":{$lt:300}});
{ "_id" : ObjectId("5b691a9835bf2db0d02756a1"), "empID" : 21, "Name" : "John", "Salary" : 200 }
> db.Employee1.find({"Salary":{$lte:300}});
{ "_id" : ObjectId("5b691a9835bf2db0d02756a1"), "empID" : 21, "Name" : "John", "Salary" : 200 }
{ "_id" : ObjectId("5b691a9835bf2db0d02756a2"), "empID" : 22, "Name" : "cloria", "Salary" : 300 }
> db.Employee1.find({"Salary":{$ne:300}});
{ "_id" : ObjectId("5b691a9835bf2db0d02756a1"), "empID" : 21, "Name" : "John", "Salary" : 200 }
{ "_id" : ObjectId("5b691a9835bf2db0d02756a3"), "empID" : 23, "Name" : "Rachel", "Salary" : 450 }
{ "_id" : ObjectId("5b691a9835bf2db0d02756a4"), "empID" : 24, "Name" : "Chandler", "Salary" : 500 }
=====================================================================
> db.Employee1.find({$and:[{"Name":"cloria"},{"empID":22}]}).pretty();
{
"_id" : ObjectId("5b691a9835bf2db0d02756a2"),
"empID" : 22,
"Name" : "cloria",
"Salary" : 300
}
=====================================================================
> db.Employee1.find({"Salary":{$gt:190},$or:[{"Name":"John"},{"Salary":200}]}).pretty();
{
"_id" : ObjectId("5b691a9835bf2db0d02756a1"),
"empID" : 21,
"Name" : "John",
"Salary" : 200
}
> db.Employee1.find({"Salary":{$gt:190},$or:[{"Name":"cloria"},{"Salary":300}]}).pretty();
{
"_id" : ObjectId("5b691a9835bf2db0d02756a2"),
"empID" : 22,
"Name" : "cloria",
"Salary" : 300
}
======================================================================
> db.Employee1.find({"Salary":{$gt:190},$or:[{"Name":"cloria"},{"Salary":200}]}).pretty();
{
"_id" : ObjectId("5b691a9835bf2db0d02756a1"),
"empID" : 21,
"Name" : "John",
"Salary" : 200
}
{

"_id" : ObjectId("5b691a9835bf2db0d02756a2"),
"empID" : 22,

Department of Computer Engineering 75


Database Management Systems Lab T.E (Computer Engineering)

"Name" : "cloria",
"Salary" : 300
}
=======================================================================
> db.Employee1.save({"_id":100,"Name":"Jesica","empID":24});
WriteResult({ "nMatched" : 0, "nUpserted" : 1, "nModified" : 0, "_id" : 100 })
> db.Employee1.find().pretty();
{
"_id" : ObjectId("5b691a9835bf2db0d02756a1"),
"empID" : 21,
"Name" : "John",
"Salary" : 200
}
{
"_id" : ObjectId("5b691a9835bf2db0d02756a2"),
"empID" : 22,
"Name" : "cloria",
"Salary" : 300
}
{
"_id" : ObjectId("5b691a9835bf2db0d02756a3"),
"empID" : 23,
"Name" : "Rachel",
"Salary" : 450
}
{
"_id" : ObjectId("5b691a9835bf2db0d02756a4"),
"empID" : 24,
"Name" : "Chandler",
"Salary" : 500
}
{ "_id" : 100, "Name" : "Jesica", "empID" : 24 }
> db.Employee1.remove({"Name":"cloria"})
WriteResult({ "nRemoved" : 1 })
> db.Employee1.find().pretty()
{
"_id" : ObjectId("5b691a9835bf2db0d02756a1"),
"empID" : 21,
"Name" : "John",
"Salary" : 200
}
{
"_id" : ObjectId("5b691a9835bf2db0d02756a3"),
"empID" : 23,
"Name" : "Rachel",
"Salary" : 450
}
{
"_id" : ObjectId("5b691a9835bf2db0d02756a4"),
"empID" : 24,
"Name" : "Chandler",
"Salary" : 500
}
{ "_id" : 100, "Name" : "Jesica", "empID" : 24 }
=================================================================
> db.Employee1.find({$and:[{$or:[{"Name":"Chandler"},{"Name":"Rachel"}]},{empID:{$gt:21}}]}).pretty();

Department of Computer Engineering 76


Database Management Systems Lab T.E (Computer Engineering)

{
"_id" : ObjectId("5b691a9835bf2db0d02756a3"),
"empID" : 23,
"Name" : "Rachel",
"Salary" : 450
}
{
"_id" : ObjectId("5b691a9835bf2db0d02756a4"),
"empID" : 24,
"Name" : "Chandler",
"Salary" : 500
}

Conclusion:
Successfully designed and developed MongoDB Queries using CRUD operations, Save method and
Logical operations.

Department of Computer Engineering 77


Database Management Systems Lab T.E (Computer Engineering)

ASSIGNMENT No: 3

Title: Implement aggregation and indexing with suitable example using MongoDB
Objective: To study and learn aggregation and indexing with suitable example using MongoDB

Requirements:
Software Requirements: MongoDB, Fedora 20, MYSQL
Hardware Requirements: CPU: Intel Core or Xeon 3GHz (or Dual Core 2GHz) or equal AMD,
Cores: Single (Dual/Quad Core is recommended), RAM: 4 GB (6 GB recommended)

Theory:

Aggregation:
Operations that process data sets and return calculated results are called aggregations. MongoDB
provides data aggregations that examine data sets and perform calculations on them. Aggregation is run
on the mongod instance to simplify application codes and limit resource requirements.
Similar to queries, aggregation operations in MongoDB use collections of documents as an input and
return results in the form of one or more documents.
The aggregation framework in MongoDB is based on data processing pipelines. Documents pass
through multi-stage pipelines and get transformed into an aggregated result. The most basic pipeline
stage in the aggregation framework provides filters that function like queries. It also provides document
transformations that modify the output document. The pipeline operations group and sort documents by
defined field or fields. In addition, they perform aggregation on arrays.
Pipeline stages can use operators to perform tasks such as calculate the average or concatenate a
string. The pipeline uses native operations within MongoDB to allow efficient data aggregation and is
the favored method for data aggregation.
db.collection.aggregate (pipeline, options)

Calculates aggregate values for the data in a collection or a view.

Parameter Type Description

A sequence of data aggregation operations or stages. See the aggregation


pipeline array
pipeline operators for details.

options document Optional. Additional options that aggregate() passes to the aggregate command.

Error Handling
If an error occurs, the aggregate() helper throws an exception.

Cursor Behavior
In the mongo shell, if the cursor returned from the db.collection.aggregate() is not assigned to a
variable using the var keyword, then the mongo shell automatically iterates the cursor up to 20

Department of Computer Engineering 78


Database Management Systems Lab T.E (Computer Engineering)

times.Cursors returned from aggregation only supports cursor methods that operate on evaluated
cursors (i.e. cursors whose first batch has been retrieved), such as the following methods:

 cursor.map()
 cursor.hasNext()
 cursor.objsLeftInBatch()
 cursor.next()
 cursor.itcount()
 cursor.toArray()
 cursor.pretty()
 cursor.forEach()

The various pipeline stages are as follows.


$project: This stage adds new fields or removes existing fields and thus restructures each document in
the stream. This stage returns one output document for each input document provided.
$match: It filters the document stream and allows only matching documents to pass into the next stage
without any modification. $match uses the standard MongoDB queries. For each input document, it
returns either one output document if there is a match or zero documents when there is no match.
$group: This stage groups documents based on the specified identifier expression and applies logic
known as accumulator expression to compute the output document.
$sort: This stage rearranges the order of the document stream using specified sort keys. The documents
remain unaltered even though the order changes. This stage provides one output document for each
input document.
$skip: This stage skips the first n documents where n is the specified skip number. It passes the
remaining documents without any modifications to the pipeline. For each input document, it returns
either zero documents for the first n documents or one document.
$limit: It passes the first n number of documents without any modifications to the pipeline. For each
input document, this stage returns either one document for the first n documents or zero documents
after the first n documents.
$unwind: It deconstructs an array field in the input documents to return a document for each element.
Each output document replaces the array with an element value. For each input document, it returns n
documents where n is the number of array elements and can be zero for an empty array.

Example
{ _id: 1, cust_id: "abc1", ord_date: ISODate("2012-11-02T17:04:11.102Z"), status: "A", amount: 50 }
{ _id: 2, cust_id: "xyz1", ord_date: ISODate("2013-10-01T17:04:11.102Z"), status: "A", amount: 100 }
{ _id: 3, cust_id: "xyz1", ord_date: ISODate("2013-10-12T17:04:11.102Z"), status: "D", amount: 25 }
{ _id: 4, cust_id: "xyz1", ord_date: ISODate("2013-10-11T17:04:11.102Z"), status: "D", amount: 125 }
{ _id: 5, cust_id: "abc1", ord_date: ISODate("2013-11-12T17:04:11.102Z"), status: "A", amount: 25 }

Group by and Calculate a Sum


The following aggregation operation selects documents with status equal to "A", groups the matching
documents by the cust_id field and calculates the total for each cust_id field from the sum of
the amount field, and sorts the results by the total field in descending order:
db.orders.aggregate([
{ $match: { status: "A" } },
{ $group: { _id: "$cust_id", total: { $sum: "$amount" } } },
{ $sort: { total: -1 } }
])

The operation returns a cursor with the following documents:


{ "_id" : "xyz1", "total" : 100 }
{ "_id" : "abc1", "total" : 75 }

Department of Computer Engineering 79


Database Management Systems Lab T.E (Computer Engineering)

Indexing:
Indexes are data structures that can store collection’s data set in a form that is easy to traverse. Queries
are efficiently executed with the help of indexes in MongoDB. Indexes help MongoDB find documents
that match the query criteria without performing a collection scan. If a query has an appropriate index,
MongoDB uses the index and limits the number of documents it examines.
Indexes store field values in the order of the value.The order in which the index entries are made
support operations, such as equality matches and range-based queries. MongoDB sorts and returns the
results by using the sequential order of the indexes. The indexes of MongoDB are similar to the indexes
in any other databases.MongoDB defines the indexes at the collection level for use in any field or
subfield.

Types of Index
MongoDB supports the following index types for querying.

1) Default _id: Each MongoDB collection contains an index on the default _id (Read as
underscore id) field. If no value is specified for _id, the language driver or the mongod (read as
mongo D) creates a _id field and provides an ObjectId (read as Object ID) value.

2) Single Field: For a single-field index and sort operation, the sort order of the index keys do not
matter. MongoDB can traverse the indexes either in the ascending or descending order.

3) Compound Index: For multiple fields, MongoDB supports user-defined indexes, such as
compound indexes. The sequential order of fields in a compound index is significant in
MongoDB.

4) Multikey Index: To index array data, MongoDB uses multikey indexes. When indexing a field
with an array value, MongoDB makes separate index entries for each array element.

5) Geospatial Index: To query geospatial data, MongoDB uses two types of indexes—2d indexes
(read as two D indexes) and 2d sphere (read as two D sphere) indexes.
Text Indexes: These indexes in MongoDB searches data string in a collection.

6) Hashed Indexes: MongoDB supports hash-based sharding and provides hashed indexes. These
indexes the hashes of the field value.

Name Description

$avg Returns an average of numerical values. Ignores non-numeric values.

Returns a value from the first document for each group. Order is only defined if the
$first
documents are in a defined order.

Returns a value from the last document for each group. Order is only defined if the documents
$last
are in a defined order.

$max Returns the highest expression value for each group.

Department of Computer Engineering 80


Database Management Systems Lab T.E (Computer Engineering)

Name Description

$min Returns the lowest expression value for each group.

$push Returns an array of expression values for each group.

Returns an array of unique expression values for each group. Order of the array elements is
$addToSet
undefined.

$stdDevPop Returns the population standard deviation of the input values.

$stdDevSamp Returns the sample standard deviation of the input values.

$sum Returns a sum of numerical values. Ignores non-numeric values.

Program:
[sinhgad@localhost ~]$ su
Password:
[root@localhost sinhgad]# cd Documents
[root@localhost Documents]# ls
5970502.zip mongodb-linux-x86_64-3.0.2 pymongo
assignment 10.docx mongodb-linux-x86_64-3.0.2.tgz report_template_final
com mysql-connector-java-5.1.46 Sample_PPT_Review1-1.pptx
eclipse mysql-connector-java-5.1.46.zip tecompsyllabus.pdf
META-INF org
[root@localhost Documents]# cd mongodb-linux-x86_64-3.0.2/bin/
[root@localhost bin]# ./mongod
=================================================================
Open in New Tab

[sinhgad@localhost bin]$ ./mongo


MongoDB shell version: 3.0.2
connecting to: test
Server has startup warnings:
2018-08-07T10:42:12.950+0530 I CONTROL [initandlisten] ** WARNING: You are running this process as the root user,
which is not recommended.
2018-08-07T10:42:12.950+0530 I CONTROL [initandlisten]
2018-08-07T10:42:12.950+0530 I CONTROL [initandlisten]
2018-08-07T10:42:12.950+0530 I CONTROL [initandlisten] ** WARNING:
/sys/kernel/mm/transparent_hugepage/enabled is 'always'.
2018-08-07T10:42:12.950+0530 I CONTROL [initandlisten] ** We suggest setting it to 'never'
2018-08-07T10:42:12.950+0530 I CONTROL [initandlisten]
2018-08-07T10:42:12.950+0530 I CONTROL [initandlisten] ** WARNING: /sys/kernel/mm/transparent_hugepage/defrag
is 'always'.
2018-08-07T10:42:12.950+0530 I CONTROL [initandlisten] ** We suggest setting it to 'never'
2018-08-07T10:42:12.950+0530 I CONTROL [initandlisten]
=======================================================================
> use gallery;
switched to db gallery

Department of Computer Engineering 81


Database Management Systems Lab T.E (Computer Engineering)

=======================================================================
> db.createCollection("music");
{ "ok" : 1 }
=======================================================================
> db.music.insert({"SrNo":1,"Name":"Akon","Song":"Lonely","Year":2005,"Status":"W"});
WriteResult({ "nInserted" : 1 })
> db.music.insert({"SrNo":2,"Name":"SeanPaul","Song":"Rockabye","Year":1996,"Status":"W"});
WriteResult({ "nInserted" : 1 })
> db.music.insert({"SrNo":3,"Name":"Pitbull","Song":"Temparature","Year":2000,"Status":"W"});
WriteResult({ "nInserted" : 1 })
> db.music.insert({"SrNo":4,"Name":"LuisFonsi","Song":"Despacito","Year":2010,"Status":"A"});
WriteResult({ "nInserted" : 1 })
> db.music.insert({"SrNo":5,"Name":"SeanPaul","Song":"Cheapthrills","Year":2015,"Status":"A"});
WriteResult({ "nInserted" : 1 })
=====================================================================
> db.music.find().pretty();
{
"_id" : ObjectId("5b692b7d0236dca616eb0ea9"),
"SrNo" : 1,
"Name" : "Akon",
"Song" : "Lonely",
"Year" : 2005,
"Status" : "W"
}
{
"_id" : ObjectId("5b692d3c0236dca616eb0eaa"),
"SrNo" : 2,
"Name" : "SeanPaul",
"Song" : "Rockabye",
"Year" : 1996,
"Status" : "W"
}
{
"_id" : ObjectId("5b692d670236dca616eb0eab"),
"SrNo" : 3,
"Name" : "Pitbull",
"Song" : "Temparature",
"Year" : 2000,
"Status" : "W"
}
{
"_id" : ObjectId("5b692da80236dca616eb0eac"),
"SrNo" : 4,
"Name" : "LuisFonsi",
"Song" : "Despacito",
"Year" : 2010,

"Status" : "A"
}
{

Department of Computer Engineering 82


Database Management Systems Lab T.E (Computer Engineering)

"_id" : ObjectId("5b692ddd0236dca616eb0ead"),
"SrNo" : 5,
"Name" : "SeanPaul",
"Song" : "Cheapthrills",
"Year" : 2015,
"Status" : "A"
}
=======================================================================
> db.music.aggregate([{$match:{Status:"W"}}])
{ "_id" : ObjectId("5b692b7d0236dca616eb0ea9"), "SrNo" : 1, "Name" : "Akon", "Song" : "Lonely", "Year" : 2005,
"Status" : "W" }
{ "_id" : ObjectId("5b692d3c0236dca616eb0eaa"), "SrNo" : 2, "Name" : "SeanPaul", "Song" : "Rockabye", "Year" : 1996,
"Status" : "W" }
{ "_id" : ObjectId("5b692d670236dca616eb0eab"), "SrNo" : 3, "Name" : "Pitbull", "Song" : "Temparature", "Year" : 2000,
"Status" : "W" }
=======================================================================
> db.music.aggregate([{$match:{Status:"W"}},{$group:{_id:"Status",total:{$sum:"$Year"}}}])
{ "_id" : "Status", "total" : 6001 }
=====================================================================
> db.music.aggregate([{$match:{Status:"W"}},{$group:{_id:"Status",total:{$avg:"$Year"}}}])
{ "_id" : "Status", "total" : 2000.3333333333333 }
======================================================================
> db.music.aggregate([{$match:{Status:"W"}},{$group:{_id:"Status",total:{$max:"$Year"}}}])
{ "_id" : "Status", "total" : 2005 }
=======================================================================
> db.music.aggregate([{$match:{Status:"W"}},{$group:{_id:"Status",total:{$min:"$Year"}}}])
{ "_id" : "Status", "total" : 1996 }
=======================================================================
> db.music.distinct("Year")
[ 2005, 1996, 2000, 2010, 2015 ]
=======================================================================
> use te;
switched to db te
=======================================================================
> db.te.insert({"Rollno":1,"Name":"a","Marks":54});
WriteResult({ "nInserted" : 1 })
> db.te.insert({"Rollno":2,"Name":"b","Marks":56});
WriteResult({ "nInserted" : 1 })
> db.te.insert({"Rollno":3,"Name":"c","Marks":64});
WriteResult({ "nInserted" : 1 })
=======================================================================
> db.te.find().pretty();
{
"_id" : ObjectId("5b6930a60236dca616eb0eae"),
"Rollno" : 1,
"Name" : "a",
"Marks" : 54

}
{

Department of Computer Engineering 83


Database Management Systems Lab T.E (Computer Engineering)

"_id" : ObjectId("5b6930b60236dca616eb0eaf"),
"Rollno" : 2,
"Name" : "b",
"Marks" : 56
}
{
"_id" : ObjectId("5b6930c50236dca616eb0eb0"),
"Rollno" : 3,
"Name" : "c",
"Marks" : 64
}
=======================================================================
> db.te.ensureIndex({"Name":1});
{
"createdCollectionAutomatically" : false,
"numIndexesBefore" : 1,
"numIndexesAfter" : 2,
"ok" : 1
}
> db.te.ensureIndex({"Name":1,"Rollno":1});
{
"createdCollectionAutomatically" : false,
"numIndexesBefore" : 2,
"numIndexesAfter" : 3,
"ok" : 1
}
=======================================================================
> db.te.getIndexes();
[
{
"v" : 1,
"key" : {
"_id" : 1
},
"name" : "_id_",
"ns" : "te.te"
},
{
"v" : 1,
"key" : {
"Name" : 1
},
"name" : "Name_1",
"ns" : "te.te"
},
{
"v" : 1,
"key" : {

"Name" : 1,

Department of Computer Engineering 84


Database Management Systems Lab T.E (Computer Engineering)

"Rollno" : 1
},
"name" : "Name_1_Rollno_1",
"ns" : "te.te"
}
]
=======================================================================
> db.te.dropIndexes();
{
"nIndexesWas" : 3,
"msg" : "non-_id indexes dropped for collection",
"ok" : 1
}

Conclusion: Studied and implemented aggregation and indexing using MongoDB

Department of Computer Engineering 85


Database Management Systems Lab T.E (Computer Engineering)

ASSIGNMENT No: 4
Title: Implement Map reduces operation with suitable example using MongoDB
Objective: To study and learn Map reduce operation with MongoDB

Requirements:
Software Requirements: MongoDB, Fedora 20, MYSQL
Hardware Requirements: CPU: Intel Core or Xeon 3GHz (or Dual Core 2GHz) or equal AMD,
Cores: Single (Dual/Quad Core is recommended), RAM: 4 GB (6 GB recommended)

Theory:

Map-Reduce:
Map-reduce is a data processing paradigm for condensing large volumes of data into useful aggregated
results. MongoDB uses mapReduce command for map-reduce operations. MapReduce is generally
used for processing large data sets.

MapReduce Command
Following is the syntax of the basic mapReduce command −

>db.collection.mapReduce(
function() {emit(key,value);}, //map function
function(key,values) {return reduceFunction}, { //reduce function
out: collection,
query: document,
sort: document,
limit: number
}
)
The map-reduce function first queries the collection, then maps the result documents to emit key-value
pairs, which is then reduced based on the keys that have multiple values.
In the above syntax −
 map is a javascript function that maps a value with a key and emits a key-value pair
 reduce is a javascript function that reduces or groups all the documents having the same key
 out specifies the location of the map-reduce query result
 query specifies the optional selection criteria for selecting documents
 sort specifies the optional sort criteria
 limit specifies the optional maximum number of documents to be returned

Department of Computer Engineering 86


Database Management Systems Lab T.E (Computer Engineering)

Example:
Consider the following map-reduce operations on a collection orders that contains documents of the
following prototype:
{
_id: ObjectId("50a8240b927d5d8b5891743c"),
cust_id: "abc123",
ord_date: new Date("Oct 04, 2012"),
status: 'A',
price: 25,
items: [ { sku: "mmm", qty: 5, price: 2.5 },
{ sku: "nnn", qty: 5, price: 2.5 } ]
}

Return the Total Price per Customer


Perform the map-reduce operation on the orders collection to group by the cust_id, and calculate the
sum of the price for each cust_id:
1. Define the map function to process each input document:
o In the function, this refers to the document that the map-reduce operation is processing.
o The function maps the price to the cust_id for each document and emits
the cust_id and price pair.
var mapFunction1 = function() {
emit(this.cust_id, this.price);
};

Program:
[sinhgad@localhost ~]$ su
Password:
[root@localhost sinhgad]# cd Documents
[root@localhost Documents]# ls
5970502.zip META-INF org
assignment 10.docx mongodb-linux-x86_64-3.0.2 pymongo
Assignment11.docx mongodb-linux-x86_64-3.0.2.tgz report_template_final
com mysql-connector-java-5.1.46 Sample_PPT_Review1-1.pptx
eclipse mysql-connector-java-5.1.46.zip tecompsyllabus.pdf
[root@localhost Documents]# cd mongodb-linux-x86_64-3.0.2/bin/
[root@localhost bin]# ./mongod
=====================================================================
Open in new Tab
[sinhgad@localhost bin]$ ./mongo
MongoDB shell version: 3.0.2
connecting to: test
Server has startup warnings:
2018-08-07T11:43:41.841+0530 I CONTROL [initandlisten] ** WARNING: You are running this process as the root user,
which is not recommended.
2018-08-07T11:43:41.841+0530 I CONTROL [initandlisten]
2018-08-07T11:43:41.841+0530 I CONTROL [initandlisten]

2018-08-07T11:43:41.841+0530 I CONTROL [initandlisten] ** WARNING:


/sys/kernel/mm/transparent_hugepage/enabled is 'always'.
2018-08-07T11:43:41.841+0530 I CONTROL [initandlisten] ** We suggest setting it to 'never'
2018-08-07T11:43:41.841+0530 I CONTROL [initandlisten]

Department of Computer Engineering 87


Database Management Systems Lab T.E (Computer Engineering)

2018-08-07T11:43:41.841+0530 I CONTROL [initandlisten] ** WARNING: /sys/kernel/mm/transparent_hugepage/defrag


is 'always'.
2018-08-07T11:43:41.841+0530 I CONTROL [initandlisten] ** We suggest setting it to 'never'
2018-08-07T11:43:41.841+0530 I CONTROL [initandlisten]
=====================================================================
> show dbs;
79 0.078GB
eddu 0.078GB
gallery 0.078GB
gridfs_example 0.078GB
local 0.078GB
mukul 0.078GB
office 0.078GB
student 0.078GB
te 0.078GB
test 0.078GB
tet1 0.078GB
tet3 0.078GB
=====================================================================
> use t1;
switched to db t1
=====================================================================
> db.createCollection("TEB");
{ "ok" : 1 }
> db.TEB.insert({"id":1,"amount":1200,"status":"a"},{"id":2,"amount":1500,"status":"b"});
WriteResult({ "nInserted" : 1 })
=====================================================================
> db.TEB.mapReduce(function(){emit(this.id,this.amount);},function(key,values){return
Array.sum(values)},{query:{id:1},out:"TEB_details"})
{
"result" : "TEB_details",
"timeMillis" : 56,
"counts" : {
"input" : 1,
"emit" : 1,
"reduce" : 0,
"output" : 1
},
"ok" : 1
}
=====================================================================
> db.TEB_details.find()
{ "_id" : 1, "value" : 1200 }
=====================================================================

Conclusion: Studied and Implemented Map reduces operation with MongoDB.

Department of Computer Engineering 88


Database Management Systems Lab T.E (Computer Engineering)

ASSIGNMENT No: 5

Title: Design and Implement any 5 query using MongoDB


Objective: Queries using MongoD
Requirements:
Software Requirements: MongoDB, Fedora 20, MYSQL
Hardware Requirements: CPU: Intel Core or Xeon 3GHz (or Dual Core 2GHz) or equal AMD,
Cores: Single (Dual/Quad Core is recommended), RAM: 4 GB (6 GB recommended)
Theory:

MongoDB crud Operations:


Create or insert operations add new documents to a collection. If the collection does not currently
exist, insert operations will create the collection. MongoDB provides the following methods to insert
documents into a collection:
db.collection.insertOne ()
db.collection.insertMany ()

In MongoDB, insert operations target a single collection. All write operations in MongoDB
are atomic on the level of a single document.

db.users.insertone (  Collection
{
Name:”sue”,  Field:value Documents
Age: 26,  Field:value
}
)

Read Operations: retrieve documents from a collection; i.e. queries a collection for documents.
MongoDB provides the following methods to read documents from a collection:
 db.users.find(  Collection
 {age:{$gt:18}}, Query criteria
 {name:1,address: 1}  Projection
).limit (5)  Cursor modifier

Update Operations:
Update operations modify existing documents in a collection. MongoDB provides the following
methods to update documents of a collection:
db.collection.updateOne()
db.collection.updateMany()
db.collection.replaceOne()
In MongoDB, update operations target a single collection. All write operations in MongoDB
are atomic on the level of a single document.
These filters use the same syntax as read operations.

Delete Operations
Delete operations remove documents from a collection. MongoDB provides the following methods to
delete documents of a collection:

Department of Computer Engineering 89


Database Management Systems Lab T.E (Computer Engineering)

db.collection.deleteOne()
db.collection.deleteMany()
In MongoDB, delete operations target a single collection. All write operations in MongoDB
are atomic on the level of a single document.

Select All Documents in a Collection: To select all documents in the collection, pass an empty
document as the query filter parameter to the find method. The query filter parameter determines the
select criteria:
db.collection.find( {} )

This operation corresponds to the following SQL statement:

SELECT * FROM collection

Specify Equality Condition

To specify equality conditions, use <field>:<value> expressions in the query filter document:

{ <field1>: <value1>, ... }

The following example selects from the inventory collection all documents where
the status equals "D":

db.inventory.find( { status: "D" } )

This operation corresponds to the following SQL statement:

SELECT * FROM inventory WHERE status = "D"

Specify Conditions Using Query Operators: A query filter document can use the query operators to
specify conditions in the following form:

{ <field1>: { <operator1>: <value1> }, ... }

The following example retrieves all documents from the inventory collection where status equals
either "A"or "D":

The operation corresponds to the following SQL statement:

SELECT * FROM inventory WHERE status in ("A", "D")

Specify AND Conditions


A compound query can specify conditions for more than one field in the collection’s documents.
Implicitly, a logical AND conjunction connects the clauses of a compound query so that the query
selects the documents in the collection that match all the conditions.

The following example retrieves all documents in the inventory collection where
the status equals "A" and qty is less than ($lt) 30:
Department of Computer Engineering 90
Database Management Systems Lab T.E (Computer Engineering)

db.inventory.find( { status: "A", qty: { $lt: 30 } } )

The operation corresponds to the following SQL statement:

SELECT * FROM inventory WHERE status = "A" AND qty < 30

Specify OR Conditions
Using the $or operator, you can specify a compound query that joins each clause with a
logical OR conjunction so that the query selects the documents in the collection that match at least one
condition.

The following example retrieves all documents in the collection where the status equals "A" or qty is
less than ($lt) 30:

db.inventory.find( { $or: [ { status: "A" }, { qty: { $lt: 30 } } ] } )

The operation corresponds to the following SQL statement:

SELECT * FROM inventory WHERE status = "A" OR qty < 30

Specify AND as well as OR Conditions

In the following example, the compound query document selects all documents in the collection where
the status equals "A" and either qty is less than ($lt) 30 or item starts with the character p:

db.inventory.find( {
Status: "A",
$or: [ { qty: { $lt: 30 } }, { item: /^p/ } ]
})

SELECT * FROM inventory WHERE status = "A" AND (qty < 30 OR item LIKE "p %")

$lt(lessthan):- For specify AND condition, An equality match on the field and less than($lt)
comparison match on field.

Example: db.inventory.find ({type:”food”,price:{$lt:9.95}})

$gt(greater than):- For specify OR conditions, the field qty has a value greater than($gt)100 or the
value of the price field is less than ($lt) 9.95

Example: db.inventory.find({type:”food”,$or:[{qty:{$gt:100}},{price:{$lt:9.95}}]})

To know current user information:


Show user;

To remove users along with all its collections you have to go through admin:
Use admin
Switched to db admin
Department of Computer Engineering 91
Database Management Systems Lab T.E (Computer Engineering)

Rename collection permanently:


Db.bank.renameCollection(“bankdata”);

Use shutdown Server ()


Use admin
db.shutdownServer( )

Program:
[sinhgad@localhost ~]$ su
Password:
[root@localhost sinhgad]# cd Documents
[root@localhost Documents]# ls
5970502.zip eclipse mongodb-linux-x86_64-3.0.2 mysql-connector-java-5.1.46 org report_template_final
tecompsyllabus.pdf
com META-INF mongodb-linux-x86_64-3.0.2.tgz mysql-connector-java-5.1.46.zip pymongo
Sample_PPT_Review1-1.pptx
[root@localhost Documents]# cd mongodb-linux-x86_64-3.0.2/bin/
[root@localhost bin]# ./mongod
---------------------------------------------------------------------------------------------------------------
Open in New Tab
[sinhgad@localhost bin]$ ./mongo
MongoDB shell version: 3.0.2
connecting to: test
Server has startup warnings:
2018-08-07T09:24:36.947+0530 I CONTROL [initandlisten] ** WARNING: You are running this process as the root user,
which is not recommended.
2018-08-07T09:24:36.947+0530 I CONTROL [initandlisten]
2018-08-07T09:24:36.961+0530 I CONTROL [initandlisten]
2018-08-07T09:24:36.961+0530 I CONTROL [initandlisten] ** WARNING:
/sys/kernel/mm/transparent_hugepage/enabled is 'always'.
2018-08-07T09:24:36.961+0530 I CONTROL [initandlisten] ** We suggest setting it to 'never'
2018-08-07T09:24:36.961+0530 I CONTROL [initandlisten]
2018-08-07T09:24:36.961+0530 I CONTROL [initandlisten] ** WARNING: /sys/kernel/mm/transparent_hugepage/defrag
is 'always'.
2018-08-07T09:24:36.961+0530 I CONTROL [initandlisten] ** We suggest setting it to 'never'
2018-08-07T09:24:36.961+0530 I CONTROL [initandlisten]
=======================================================================
> use office;
switched to db office
=======================================================================
> db.createCollection("Employee");
{ "ok" : 0, "errmsg" : "collection already exists", "code" : 48 }

> db.createCollection("Employee1");
{ "ok" : 1 }
=======================================================================
>
db.Employee1.insert([{"empID":21,"Name":"John","Salary":200},{"empID":22,"Name":"cloria","Salary":300},{"empID":
23,"Name":"Rachel","Salary":400},{"empID":24,"Name":"Chandler","Salary":500}]);

Department of Computer Engineering 92


Database Management Systems Lab T.E (Computer Engineering)

BulkWriteResult({
"writeErrors" : [ ],
"writeConcernErrors" : [ ],
"nInserted" : 4,
"nUpserted" : 0,
"nMatched" : 0,
"nModified" : 0,
"nRemoved" : 0,
"upserted" : [ ]
})
=======================================================================
> db.Employee1.find().pretty();
{
"_id" : ObjectId("5b691a9835bf2db0d02756a1"),
"empID" : 21,
"Name" : "John",
"Salary" : 200
}
{
"_id" : ObjectId("5b691a9835bf2db0d02756a2"),
"empID" : 22,
"Name" : "cloria",
"Salary" : 300
}
{
"_id" : ObjectId("5b691a9835bf2db0d02756a3"),
"empID" : 23,
"Name" : "Rachel",
"Salary" : 400
}
{
"_id" : ObjectId("5b691a9835bf2db0d02756a4"),
"empID" : 24,
"Name" : "Chandler",
"Salary" : 500
}
=======================================================================
> db.Employee1.update({"Name":"Rachel"},{$set:{"Salary":450}});
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.Employee1.find().pretty();
{
"_id" : ObjectId("5b691a9835bf2db0d02756a1"),
"empID" : 21,
"Name" : "John",

"Salary" : 200
}
{
"_id" : ObjectId("5b691a9835bf2db0d02756a2"),
"empID" : 22,

Department of Computer Engineering 93


Database Management Systems Lab T.E (Computer Engineering)

"Name" : "cloria",
"Salary" : 300
}
{
"_id" : ObjectId("5b691a9835bf2db0d02756a3"),
"empID" : 23,
"Name" : "Rachel",
"Salary" : 450
}
{
"_id" : ObjectId("5b691a9835bf2db0d02756a4"),
"empID" : 24,
"Name" : "Chandler",
"Salary" : 500
}
====================================================================
> db.Employee1.find({"Salary":{$gt:300}});
{ "_id" : ObjectId("5b691a9835bf2db0d02756a3"), "empID" : 23, "Name" : "Rachel", "Salary" : 450 }
{ "_id" : ObjectId("5b691a9835bf2db0d02756a4"), "empID" : 24, "Name" : "Chandler", "Salary" : 500 }
> db.Employee1.find({"Salary":{$gte:300}});
{ "_id" : ObjectId("5b691a9835bf2db0d02756a2"), "empID" : 22, "Name" : "cloria", "Salary" : 300 }
{ "_id" : ObjectId("5b691a9835bf2db0d02756a3"), "empID" : 23, "Name" : "Rachel", "Salary" : 450 }
{ "_id" : ObjectId("5b691a9835bf2db0d02756a4"), "empID" : 24, "Name" : "Chandler", "Salary" : 500 }
> db.Employee1.find({"Salary":{$lt:300}});
{ "_id" : ObjectId("5b691a9835bf2db0d02756a1"), "empID" : 21, "Name" : "John", "Salary" : 200 }
> db.Employee1.find({"Salary":{$lte:300}});
{ "_id" : ObjectId("5b691a9835bf2db0d02756a1"), "empID" : 21, "Name" : "John", "Salary" : 200 }
{ "_id" : ObjectId("5b691a9835bf2db0d02756a2"), "empID" : 22, "Name" : "cloria", "Salary" : 300 }
> db.Employee1.find({"Salary":{$ne:300}});
{ "_id" : ObjectId("5b691a9835bf2db0d02756a1"), "empID" : 21, "Name" : "John", "Salary" : 200 }
{ "_id" : ObjectId("5b691a9835bf2db0d02756a3"), "empID" : 23, "Name" : "Rachel", "Salary" : 450 }
{ "_id" : ObjectId("5b691a9835bf2db0d02756a4"), "empID" : 24, "Name" : "Chandler", "Salary" : 500 }
=====================================================================
> db.Employee1.find({$and:[{"Name":"cloria"},{"empID":22}]}).pretty();
{
"_id" : ObjectId("5b691a9835bf2db0d02756a2"),
"empID" : 22,
"Name" : "cloria",
"Salary" : 300
}
=====================================================================
> db.Employee1.find({"Salary":{$gt:190},$or:[{"Name":"John"},{"Salary":200}]}).pretty();
{
"_id" : ObjectId("5b691a9835bf2db0d02756a1"),
"empID" : 21,

"Name" : "John",
"Salary" : 200
}
> db.Employee1.find({"Salary":{$gt:190},$or:[{"Name":"cloria"},{"Salary":300}]}).pretty();

Department of Computer Engineering 94


Database Management Systems Lab T.E (Computer Engineering)

{
"_id" : ObjectId("5b691a9835bf2db0d02756a2"),
"empID" : 22,
"Name" : "cloria",
"Salary" : 300
}
======================================================================
> db.Employee1.find({"Salary":{$gt:190},$or:[{"Name":"cloria"},{"Salary":200}]}).pretty();
{
"_id" : ObjectId("5b691a9835bf2db0d02756a1"),
"empID" : 21,
"Name" : "John",
"Salary" : 200
}
{
"_id" : ObjectId("5b691a9835bf2db0d02756a2"),
"empID" : 22,
"Name" : "cloria",
"Salary" : 300
}
=======================================================================
> db.Employee1.save({"_id":100,"Name":"Jesica","empID":24});
WriteResult({ "nMatched" : 0, "nUpserted" : 1, "nModified" : 0, "_id" : 100 })
> db.Employee1.find().pretty();
{
"_id" : ObjectId("5b691a9835bf2db0d02756a1"),
"empID" : 21,
"Name" : "John",
"Salary" : 200
}
{
"_id" : ObjectId("5b691a9835bf2db0d02756a2"),
"empID" : 22,
"Name" : "cloria",
"Salary" : 300
}
{
"_id" : ObjectId("5b691a9835bf2db0d02756a3"),
"empID" : 23,
"Name" : "Rachel",
"Salary" : 450
}
{
"_id" : ObjectId("5b691a9835bf2db0d02756a4"),
"empID" : 24,
"Name" : "Chandler",

"Salary" : 500
}
{ "_id" : 100, "Name" : "Jesica", "empID" : 24 }

Department of Computer Engineering 95


Database Management Systems Lab T.E (Computer Engineering)

> db.Employee1.remove({"Name":"cloria"})
WriteResult({ "nRemoved" : 1 })
> db.Employee1.find().pretty()
{
"_id" : ObjectId("5b691a9835bf2db0d02756a1"),
"empID" : 21,
"Name" : "John",
"Salary" : 200
}
{
"_id" : ObjectId("5b691a9835bf2db0d02756a3"),
"empID" : 23,
"Name" : "Rachel",
"Salary" : 450
}
{
"_id" : ObjectId("5b691a9835bf2db0d02756a4"),
"empID" : 24,
"Name" : "Chandler",
"Salary" : 500
}
{ "_id" : 100, "Name" : "Jesica", "empID" : 24 }
=================================================================
> db.Employee1.find({$and:[{$or:[{"Name":"Chandler"},{"Name":"Rachel"}]},{empID:{$gt:21}}]}).pretty();
{
"_id" : ObjectId("5b691a9835bf2db0d02756a3"),
"empID" : 23,
"Name" : "Rachel",
"Salary" : 450
}
{
"_id" : ObjectId("5b691a9835bf2db0d02756a4"),
"empID" : 24,
"Name" : "Chandler",
"Salary" : 500}

Department of Computer Engineering 96


Database Management Systems Lab T.E (Computer Engineering)

ASSIGNMENT NO: 6

Title: Create simple objects and array objects using JSON


Objective: To create simple objects and array objects using JSON
Requirements:
Software Requirements: MongoDB, Fedora 20, MYSQL
Hardware Requirements: CPU: Intel Core or Xeon 3GHz (or Dual Core 2GHz) or equal AMD,
Cores: Single (Dual/Quad Core is recommended), RAM: 4 GB (6 GB recommended)

Theory:
Introduction to JSON:
JSON or JavaScript Object Notation is a lightweight text-based open standard designed for human-
readable data interchange. Conventions used by JSON are known to programmers, which include C,
C++, Java, Python, Perl, etc.
 JSON stands for JavaScript Object Notation.
 The format was specified by Douglas Crockford.
 It was designed for human-readable data interchange.
 It has been extended from the JavaScript scripting language.
 The filename extension is .json.
 JSON Internet Media type is application/json.
 The Uniform Type Identifier is public.json.

Uses of JSON
 It is used while writing JavaScript based applications that include browser extensions and
websites.
 JSON format is used for serializing and transmitting structured data over network connection.
 It is primarily used to transmit data between a server and web applications.
 Web services and APIs use JSON format to provide public data.
 It can be used with modern programming languages.

Characteristics of JSON

 JSON is easy to read and write.


 It is a lightweight text-based interchange format.
 JSON is language independent.
Simple Example in JSON
The following example shows how to use JSON to store information related to books based on their
topic and edition.
{
"book": [
{
"id":"01",
"language": "Java",
"edition": "third",
"author": "Herbert Schildt"
},
{
"id":"07",

Department of Computer Engineering 97


Database Management Systems Lab T.E (Computer Engineering)

"language": "C++",
"edition": "second",
"author": "E.Balagurusamy"
}
]
}

After understanding the above program, we will try another example. Let's save the below code
as json.htm –

<html>
<head>
<title>JSON example</title>

<script language = "javascript" >

var object1 = { "language" : "Java", "author" : "herbert schildt" };


document.write("<h1>JSON with JavaScript example</h1>");
document.write("<br>");
document.write("<h3>Language = " + object1.language+"</h3>");
document.write("<h3>Author = " + object1.author+"</h3>");

var object2 = { "language" : "C++", "author" : "E-Balagurusamy" };


document.write("<br>");
document.write("<h3>Language = " + object2.language+"</h3>");
document.write("<h3>Author = " + object2.author+"</h3>");

document.write("<hr />");
document.write(object2.language + " programming language can be studied " + "from book written by " +
object2.author);
document.write("<hr />");
</script>
</head>
<body>
</body>
</html>
Now open json.htm using IE or any other javascript enabled browser that produces the following
result.

Department of Computer Engineering 98


Database Management Systems Lab T.E (Computer Engineering)

JSON supports the following two data structures −


 Collection of name/value pairs − This Data Structure is supported by different programming
languages.
 Ordered list of values − It includes array, list, vector or sequence etc.
JSON format supports the following data types −
S. No. Type & Description

Number
1
double- precision floating-point format in JavaScript

String
2
double-quoted Unicode with backslash escaping

Boolean
3
true or false

Array
4
an ordered sequence of values

Value
5
it can be a string, a number, true or false, null etc

Object
6
an unordered collection of key:value pairs

Whitespace
7
can be used between any pair of tokens

null
8
empty

Creating Simple Objects

JSON objects can be created with JavaScript. Let us see the various ways of creating JSON objects
using JavaScript −
 Creation of an empty Object −
var JSONObj = {};
 Creation of a new Object −
var JSONObj = new Object();
 Creation of an object with attribute bookname with value in string, attribute price with
numeric value. Attribute is accessed by using '.' Operator −
var JSONObj = { "bookname ":"VB BLACK BOOK", "price":500 };
This is an example that shows creation of an object in javascript using JSON, save the below code
as json_object.htm –

Department of Computer Engineering 99


Database Management Systems Lab T.E (Computer Engineering)

<html>
<head>
<title>Creating Object JSON with JavaScript</title>

<script language = "javascript" >

var JSONObj = { "name" : "tutorialspoint.com", "year" : 2005 };

document.write("<h1>JSON with JavaScript example</h1>");


document.write("<br>");
document.write("<h3>Website Name = "+JSONObj.name+"</h3>");
document.write("<h3>Year = "+JSONObj.year+"</h3>");
</script>
</head>
<body>
</body>
</html>
Now let's try to open Json Object using IE or any other javaScript enabled browser. It produces the
following result −

Creating Array Objects


The following example shows creation of an array object in javascript using JSON, save the below
code as json_array_object.htm –
<html>
<head>
<title>Creation of array object in javascript using JSON</title>

<script language = "javascript" >

document.writeln("<h2>JSON array object</h2>");

var books = { "Pascal" : [


{ "Name" : "Pascal Made Simple", "price" : 700 },
{ "Name" : "Guide to Pascal", "price" : 400 }],

"Scala" : [
{ "Name" : "Scala for the Impatient", "price" : 1000 },
{ "Name" : "Scala in Depth", "price" : 1300 }]
}

var i = 0
document.writeln("<table border = '2'><tr>");

for(i = 0;i<books.Pascal.length;i++){

Department of Computer Engineering 100


Database Management Systems Lab T.E (Computer Engineering)

document.writeln("<td>");
document.writeln("<table border = '1' width = 100 >");
document.writeln("<tr><td><b>Name</b></td><td width = 50>" + books.Pascal[i].Name+"</td></tr>");
document.writeln("<tr><td><b>Price</b></td><td width = 50>" + books.Pascal[i].price +"</td></tr>");
document.writeln("</table>");
document.writeln("</td>");
}

for(i = 0;i<books.Scala.length;i++){
document.writeln("<td>");
document.writeln("<table border = '1' width = 100 >");
document.writeln("<tr><td><b>Name</b></td><td width = 50>" + books.Scala[i].Name+"</td></tr>");
document.writeln("<tr><td><b>Price</b></td><td width = 50>" + books.Scala[i].price+"</td></tr>");
document.writeln("</table>");
document.writeln("</td>");
}

document.writeln("</tr></table>");

</script>

</head>

<body>
</body>
</html>

Now let's try to open Json Array Object using IE or any other javaScript enabled browser. It produces
the following result –

Conclusion: Successfully implemented objects and array objects using JSON

Department of Computer Engineering 101


Database Management Systems Lab T.E (Computer Engineering)

ASSIGNMENT NO: 7

Title: Encode and Decode JSON Objects using Java/Perl/PHP/Python/Ruby


Objective: To encode and decode the JSON objects

Requirements:
Software Requirements: MongoDB, Fedora 20, MYSQL
Hardware Requirements: CPU: Intel Core or Xeon 3GHz (or Dual Core 2GHz) or equal AMD,
Cores: Single (Dual/Quad Core is recommended), RAM: 4 GB (6 GB recommended)
Theory:
Mapping between JSON and Java entities
JSON simply maps entities from the left side to the right side while decoding or parsing, and maps
entities from the right to the left while encoding.
JSON Java

string java.lang.String

number java.lang.Number

true|false java.lang.Boolean

null null

array java.util.List

object java.util.Map

On decoding, the default concrete class of java.util. List is org.json.simple.JSONArray and the default
concrete class of java.util.Map is org.json.simple.JSONObject.
Encoding JSON in Java: Following is a simple example to encode a JSON object using Java JSON
Object which is a subclass of java.util.HashMap. No ordering is provided. If you need the strict
ordering of elements, use JSONValue.toJSONString (map) method with ordered map implementation
such as java.util.LinkedHashMap.
Import org.json.simple.JSONObject;
class JsonEncodeDemo {
public static void main(String[] args){
JSONObject obj = new JSONObject();

obj.put("name", "foo");
obj.put("num", new Integer(100));
obj.put("balance", new Double(1000.21));
obj.put("is_vip", new Boolean(true));

System.out.print(obj);
}
}

On compiling and executing the above program the following result will be generated −
{"balance": 1000.21, "num":100, "is_vip":true, "name":"foo"}

Department of Computer Engineering 102


Database Management Systems Lab T.E (Computer Engineering)

Following is another example that shows a JSON object streaming using Java JSONObject −
import org.json.simple.JSONObject;

class JsonEncodeDemo {

public static void main(String[] args){

JSONObject obj = new JSONObject();

obj.put("name","foo");
obj.put("num",new Integer(100));
obj.put("balance",new Double(1000.21));
obj.put("is_vip",new Boolean(true));

StringWriter out = new StringWriter();


obj.writeJSONString(out);

String jsonText = out.toString();


System.out.print(jsonText);
}
}
On compiling and executing the above program, the following result is generated
{"balance": 1000.21, "num":100, "is_vip":true, "name":"foo"}
Decoding JSON in Java:
The following example makes use of JSONObject and JSONArray where JSONObject is a
java.util.Map and JSONArray is a java.util.List, so you can access them with standard operations of
Map or List.
import org.json.simple.JSONObject;
import org.json.simple.JSONArray;
import org.json.simple.parser.ParseException;
import org.json.simple.parser.JSONParser;

class JsonDecodeDemo {
public static void main(String[] args){

JSONParser parser = new JSONParser();


String s = "[0,{\"1\":{\"2\":{\"3\":{\"4\":[5,{\"6\":7}]}}}}]";

try{
Object obj = parser.parse(s);
JSONArray array = (JSONArray)obj;

System.out.println("The 2nd element of array");


System.out.println(array.get(1));
System.out.println();

JSONObject obj2 = (JSONObject)array.get(1);


System.out.println("Field \"1\"");

Department of Computer Engineering 103


Database Management Systems Lab T.E (Computer Engineering)

System.out.println(obj2.get("1"));

s = "{}";
obj = parser.parse(s);
System.out.println(obj);

s = "[5,]";
obj = parser.parse(s);
System.out.println(obj);

s = "[5,,2]";
obj = parser.parse(s);
System.out.println(obj);
}catch(ParseException pe){

System.out.println("position: " + pe.getPosition());


System.out.println(pe);
}
}
}

On compiling and executing the above program, the following result will be generated

The 2nd element of array


{"1":{"2":{"3":{"4":[5,{"6":7}]}}}}

Field "1"
{"2":{"3":{"4":[5,{"6":7}]}}}
{}
[5]
[5,2]

Conclusion: Successfully implemented encoding and decoding the JSON objects using Java

Department of Computer Engineering 104


Database Management Systems Lab T.E (Computer Engineering)

GROUP C

Department of Computer Engineering 105


Database Management Systems Lab T.E (Computer Engineering)

ASSIGNMENT NO.: 1

Title: Write a program to implement MongoDB database connectivity with PHP/ python/Java
Implement Database navigation operations (add, delete, edit etc. ) using ODBC/JDBC.
Objective: To study and perform MongoDB database connectivity with Java and perform database
navigation operations.

Requirements:
Software Requirements: Eclipse, JDK 1.6, MongoDB, MongoDB-Java-Driver, Fedora 20
Hardware Requirements: Minimum 2GB RAM.

Theory:
Introduction:
MongoDB is the leading NoSQL database system which has become very popular for recent years due
to its dynamic schema nature and advantages over big data like high performance, horizontal
scalability, replication, etc. Unlike traditional relational database systems which provide JDBC-
compliant drivers, MongoDB comes with its own non-JDBC driver called Mongo Java Driver.
MongoDB can be used with Java programs by using:
1. JDBC API: It can be used to interact with MongoDB from Java, or
2. Mongo Java Driver API.

1. Connectivity using JDBC API:-


Installation Steps:
Before using MongoDB in Java programs, make sure to have MongoDB JDBC driver and Java set up
on the machine. Now, following are the steps to set up MongoDB JDBC driver:
 Download the mongo.jar file. Make sure to download the latest release of it.
 Include the mongo.jar into the classpath.

Steps for including MongoDB-Java-Driver in Eclipse:


In Eclipse perform following steps:
1. File - New – Java Project –Give Project Name – ok
2. In project Explorer window- right click on project namenew- class- give Class name- ok
3. In project Explorer window- right click on project nameBuild path- Configure build path- Libraries-
Add External Jar - MongoDB-Java-Driver
4. Start Mongo server before running the program.

Steps for connecting MongoDB with Java and performing navigation operations:
1) Import package:
import com.mongodb.*;

2) Create connection:
To connect database, specify the database name. If the database doesn't exist then MongoDB creates it
automatically.

MongoClient mongo = new MongoClient( "localhost" , 27017 );

Department of Computer Engineering 106


Database Management Systems Lab T.E (Computer Engineering)

3) Create Database:
DB db = mongo.getDB("database name");

4) Create Collection:
To create a collection, createCollection() method of com.mongodb.client.MongoDatabase class is used.
DBCollection coll = db.getCollection(“Collection Name");

5) Insert Document:
To insert a document into MongoDB, insert() method of com.mongodb.client.MongoCollection class is
used.

BasicDBObject d1 = new BasicDBObject(“rno“,“1”).append(“name", “Monika"). append(“age", “17”)


BasicDBObject d2 = new BasicDBObject(“rno“,“2”).append(“name", “Roshan"). append(“age", “18”)
coll.insert(d1);
coll.insert(d2);

6) Display document:
To select all documents from the collection, find() method is used. This method returns a cursor, so you
need to iterate this cursor.

DBCursor cursor = coll.find();


while (cursor.hasNext())
{
System.out.println(cursor.next());
}

7) Update Document:
To update a document from the collection, updateOne() method is used.

• BasicDBObject query = new BasicDBObject();


• query.put("name", “Monika");
• BasicDBObject newDocument = new BasicDBObject();
• newDocument.put("name", “Ragini");
• BasicDBObject updateObj = new BasicDBObject();
• updateObj.put("$set", newDocument);
• Coll.update(query, updateObj);

8) Remove document:
BasicDBObject searchQuery = new BasicDBObject();
searchQuery.put("name", “Monika");
Coll.remove(searchQuery);

Example:
import com.mongodb.*;
public class conmongo {

public static void main(String[] args) {


try {
Department of Computer Engineering 107
Database Management Systems Lab T.E (Computer Engineering)

MongoClient mongoClient = new MongoClient( "localhost" , 27017 );

DB db = mongoClient.getDB( "mydb" );
DBCollection coll = db.createCollection(“Stud",null);
BasicDBObject doc1 = new BasicDBObject("rno","1").append("name",“Mona");
BasicDBObject doc2 = new BasicDBObject("rno","2").append("name","swati");
coll.insert(doc1);
coll.insert(doc2);
DBCursor cursor = coll.find(searchQuery);
while (cursor.hasNext())
{
System.out.println(cursor.next());
}
BasicDBObject query = new BasicDBObject();
query.put("name", “Monika");
BasicDBObject N1 = new BasicDBObject();
N1.put("name", “Ragini");
BasicDBObject S1= new BasicDBObject();
S1.put("$set", newDocument);
coll.update(query, S1);
BasicDBObject R1 = new BasicDBObject();
R1.put("name", “Monika");
coll.remove(R1);
}
catch(Exception e)
{
e.printStackTrace();
}
}
}

2. Connectivity using Mongo Java Driver:-


Steps for Connectivity using Mongo Java Driver:

1. Downloading Mongo Java Driver


The JAR file name is mongo-java-driver-VERSION.jar. Copy the downloaded JAR file into your
classpath.

2. Connecting to MongoDB using MongoClient


The MongoClient class is used to make a connection with a MongoDB server and perform database-
related operations. Here are some examples:
 Creating a MongoClient instance that connects to a default MongoDB server running on
localhost and default port:
MongoClient mongoClient = new MongoClient();

 Connecting to a named MongoDB server listening on the default port (27017):

MongoClient mongoClient = new MongoClient("localhost");


Department of Computer Engineering 108
Database Management Systems Lab T.E (Computer Engineering)

Or:
MongoClient mongoClient = new MongoClient("db1.server.com");

Connecting to a named MongoDB server listening on a specific port:


MongoClient mongoClient = new MongoClient("localhost", 27017);
Or:
MongoClient mongoClient = new MongoClient("db1.server.com", 27018);

 Connecting to a replica set of servers:


List<ServerAddress> seeds = new ArrayList<ServerAddress>();
seeds.add(new ServerAddress("db1.server.com", 27017));
seeds.add(new ServerAddress("db2.server.com", 27018));
seeds.add(new ServerAddress("db3.server.com", 27019));
MongoClient mongoClient = new MongoClient(seeds);

After the connection is established, we can obtain a database and make authentication (if the server is
running in secure mode), for example:
MongoClient mongoClient = new MongoClient();
DB db = mongoClient.getDB("test");

char[] password = new char[] {'s', 'e', 'c', 'r', 'e', 't'};
boolean authenticated = db.authenticate("root", password);

if (authenticated) {
System.out.println("Successfully logged in to MongoDB!");
}
else
{
System.out.println("Invalid username/password");
}
By default, MongoDB server is running in trusted mode which doesn’t require authentication.

3. Using MongoDB connection string URI


It’s also possible to use a String that represents a database connection URI to connect to the MongoDB
server, for example:
String dbURI = "mongodb://localhost";
MongoClient mongoClient = new MongoClient(new MongoClientURI(dbURI));
Syntax of the URI is as follows:
mongodb://[username:password@]host1[:port1][,host2[:port2],...[,hostN[:portN]]][/[database][?options
]]
Here are some connection string URI examples:
 Connecting to the MongoDB server running on localhost at the default port:
mongodb://localhost
 Connecting to the admin database on a named MongoDB server db1.server.com running
on port 27027 with user rootand password secret:

Department of Computer Engineering 109


Database Management Systems Lab T.E (Computer Engineering)

mongodb://root:secret@db1.server.com:27027
 Connecting to the users database on server db2.server.com:
mongodb://db2.server.com/users
 Connecting to the products database on a named MongoDB
server db3.server.com running on port 27027 with user tom and password secret:
mongodb://tom:secret@db3.server.com:27027/products
 Connecting to a replica set of three servers:
mongodb://db1.server.com,db2.server.com,db3.server.com

Program:
Steps:
1. Open Eclipse.
2. FileNewJava ProjectNextEnter project name: assign16nextFinish
3. If package explorer is invisible then follow the following steps:
Windowshow viewselect package Explorer (Can see project name)
4. Right click on project nameSelect new Class Give class name Student (name of class should be the name of database
created in terminal)ok
5. Download mongo-java-driver-2.10.1.jar file
Procedure to add jar file:
1.In project explorer window right click on project nameSelect Build pathConfigure Build path(open the configuration
window automatically)select library tabclick on add external jar buttonselect mongo-java-driver-2.10.1.jar file.
6. Open terminalcreate database college in MongoDBcreate table Student. MongoDB code is as follows:
[sinhgad@localhost ~]$ su
Password:
[root@localhost sinhgad]# cd Documents
[root@localhost Documents]# ls
abhi.asm DBMS mongo-java-driver-2.12.2.jar
abhishek Dining.java overlap
abhishek.asm EL-III Ass_A1 overlap.asm~
abhishek.o jdk-8u161-nb-8_2-linux-x64.sh overlap.o
add.asm Link to sachin.cpp overlapp.asm
a.out mongo S151024282.cpp
Assignment 9.docx mongodb-linux-x86_64-2.6.3 sachin.cpp~
cloudsim-3.0.2 mongodb-linux-x86_64-3.0.2 vishal
cloudsim-3.0.2.jar mongo-java-driver-2.12.2
[root@localhost Documents]# cd mongodb-linux-x86_64-3.0.2/bin/
[root@localhost bin]# ./mongod
2018-08-17T08:50:19.338+0530 I JOURNAL [initandlisten] journal dir=/data/db/journal
2018-08-17T08:50:19.709+0530 I CONTROL [initandlisten] ** WARNING: /sys/kernel/mm/transparent_hugepage/defrag
is 'always'.
2018-08-17T09:08:19.182+0530 I NETWORK [conn2] end connection 127.0.0.1:47754 (1 connection now open)

Open New Tab:


[sinhgad@localhost bin]$ ./mongo
MongoDB shell version: 3.0.2
connecting to: test
Server has startup warnings:
2018-08-17T08:50:19.709+0530 I CONTROL [initandlisten] ** We suggest setting it to 'never'
2018-08-17T08:50:19.709+0530 I CONTROL [initandlisten]

> use college;


switched to db college

Department of Computer Engineering 110


Database Management Systems Lab T.E (Computer Engineering)

> db.createCollection("Student");
{ "ok" : 1 }

> db.Student.insert([{"rollno":1,"name":"abc"},{"rollno":2,"name":"def"}]);
BulkWriteResult({
"writeErrors" : [ ],
"writeConcernErrors" : [ ],
"nInserted" : 2,
"nUpserted" : 0,
"nMatched" : 0,
"nModified" : 0,
"nRemoved" : 0,
"upserted" : [ ]
})

> db.Student.find().pretty();
{
"_id" : ObjectId("5b763fea9472e3780266978e"),
"rollno" : 1,
"name" : "abc"
}
{
"_id" : ObjectId("5b763fea9472e3780266978f"),
"rollno" : 2,
"name" : "def"
}

7. Open eclipse (containing project) and enter below code in class file Student
Student.java file (Create in Eclipse)

package assign16;

import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.MongoClient;

import java.util.Set;

public class Student


{
public static void main(String args[]) throws Exception
{
MongoClient mongoClient=new MongoClient("localhost",27017);
DB db=mongoClient.getDB("college");

//college is the name of database


Set<String> colls=db.getCollectionNames();
for(String s:colls)
{
System.out.println(s);
}
DBCollection coll=db.getCollection("Student");
DBCursor cur=coll.find();
int i=1;
while(cur.hasNext())

Department of Computer Engineering 111


Database Management Systems Lab T.E (Computer Engineering)

{
System.out.println(cur.next());
i++;
}

Output:-
Student
system.indexes
{ "_id" : { "$oid" : "5b763fea9472e3780266978e"} , "rollno" : 1.0 , "name" : "abc"}
{ "_id" : { "$oid" : "5b763fea9472e3780266978f"} , "rollno" : 2.0 , "name" : "def"}

Conclusion: Successfully performed MongoDB database connectivity with Java and performed
database navigation operations.

Department of Computer Engineering 112


Database Management Systems Lab T.E (Computer Engineering)

ASSIGNMENT NO.: 2

Title: Implement MYSQL/Oracle database connectivity with PHP/ python/Java. Implement Database
navigation operations (add, delete, edit,) using ODBC/JDBC.

Objective: To perform MySQL database connectivity with Java and perform database navigation
operations using JDBC-ODBC Driver.

Requirements:
Software Requirements: Eclipse, JDK 1.6, MySQL, Java-MySQL Connector, Fedora 20.
Hardware Requirements: Minimum 2GB RAM.

Theory:
Introduction to JDBC
Java Database Connectivity (JDBC) is an Application Programming Interface (API) used to connect
Java application with Database. JDBC is used to interact with various type of Database such as Oracle,
MS Access, My SQL and SQL Server. JDBC can also be defined as the platform-independent interface
between a relational database and Java programming. It allows java program to execute SQL statement
and retrieve result from database.

JDBC Driver:-
JDBC Driver is required to process SQL requests and generate result. The following are the different
types of driver available in JDBC.
 Type-1 Driver or JDBC-ODBC bridge
 Type-2 Driver or Native API or Partly Java Driver
 Type-3 Driver or Network Protocol Driver
 Type-4 Driver or Thin Driver or Pure Java Driver

1) Type-1: JDBC-ODBC Bridge Driver:


Type-1 Driver acts as a bridge between JDBC and other database connectivity mechanism (ODBC).
This driver converts JDBC calls into ODBC calls and redirects the request to the ODBC driver.

Fig.: JDBC-ODBC Bridge Driver

Department of Computer Engineering 113


Database Management Systems Lab T.E (Computer Engineering)

3) Type 2: JDBC-Native API:


In a Type 2 driver, JDBC API calls are converted into native C/C++ API calls, which are unique to the
database. These drivers are typically provided by the database vendors and used in the same manner as
the JDBC-ODBC Bridge. The vendor-specific driver must be installed on each client machine. If we
change the Database, we have to change the native API, as it is specific to a database and they are
mostly obsolete now, but you may realize some speed increase with a Type 2 driver, because it
eliminates ODBC’s overhead.

Fig.: JDBC Native API Driver

4) Type 3: Network Protocol Driver:


In a Type 3 driver, a three-tier approach is used to access databases. The JDBC clients use standard
network sockets to communicate with a middleware application server. The socket information is then
translated by the middleware application server into the call format required by the DBMS, and
forwarded to the database server. This kind of driver is extremely flexible, since it requires no code
installed on the client and a single driver can actually provide access to multiple databases.

Fig.: Network Protocol Driver

Department of Computer Engineering 114


Database Management Systems Lab T.E (Computer Engineering)

4) Type 4: Pure Java:


In a Type 4 driver, a pure Java-based driver communicates directly with the vendor's database through
socket connection. This is the highest performance driver available for the database and is usually
provided by the vendor itself.
This kind of driver is extremely flexible, we don't need to install special software on the client or
server. Further, these drivers can be downloaded dynamically.

Fig.: Pure Java Driver

Installation Steps:-
In Eclipse perform following steps:
1. File - New – Java Project –Give Project Name – ok
2. In project Explorer window- right click on project name-new- class- give Class name- ok
3. In project Explorer window- right click on project name- Build path- Configure build path-
Libraries- Add External Jar - Java-MySQL Connector
4. In MySQL, create one database and in that database create a table.

Steps for connecting MySQL database with Java:


The following 5 steps are the basic steps involve in connecting a Java application with Database using
JDBC.
1. Register the Driver
2. Create a Connection
3. Create SQL Statement
4. Execute SQL Statement
5. Closing the connection

Department of Computer Engineering 115


Database Management Systems Lab T.E (Computer Engineering)

1) Register the Driver


Class.forName() is used to load the driver class explicitly.
Example to register with JDBC-ODBC Driver
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

2) Create a Connection
getConnection() method of DriverManager class is used to create a connection.
Syntax:
getConnection(String url)
getConnection(String url, String username, String password)
getConnection(String url, Properties info)
Example:
Connection con =
DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:XE","username","password");

3) Create SQL Statement


createStatement() method is invoked on current Connection object to create a SQL Statement.
Syntax:
public Statement createStatement() throws SQLException
Example to create a SQL statement:
Statement s=con.createStatement();

4) Execute SQL Statement


executeQuery() method of Statement interface is used to execute SQL statements.
Syntax:
public ResultSet executeQuery(String query) throws SQLException
Example:
ResultSet rs=s.executeQuery("select * from user");
while(rs.next())
{
System.out.println(rs.getString(1)+" "+rs.getString(2));
}

Department of Computer Engineering 116


Database Management Systems Lab T.E (Computer Engineering)

5) Closing the connection


After executing SQL statement you need to close the connection and release the session.
The close() method of Connection interface is used to close the connection.
Syntax:
public void close() throws SQLException
Example of closing a connection:
con.close();

Example of Connectivity:
importjava.sql.*;
importjava.util.*;
class Main
{
public static void main(String a[])
{
//Creating the connection
String url = "jdbc:oracle:thin:@localhost:1521:xe";
String user = "system";
String pass = "12345";

//Entering the data


Scanner k = new Scanner(System.in);
System.out.println("enter name");
String name = k.next();
System.out.println("enter roll no");
int roll = k.nextInt();
System.out.println("enter class");
String cls = k.next();

//Inserting data using SQL query


String sql = "insert into student1 values('"+name+"',"+roll+",'"+cls+"')";
Connection con=null;
try
{
DriverManager.registerDriver(new oracle.jdbc.OracleDriver());

//Reference to connection interface


con = DriverManager.getConnection(url,user,pass);

Statement st = con.createStatement();
int m = st.executeUpdate(sql);
if (m == 1)
System.out.println("inserted successfully : "+sql);
else
System.out.println("insertion failed");
con.close();
}
catch(Exception ex)
Department of Computer Engineering 117
Database Management Systems Lab T.E (Computer Engineering)

{
System.err.println(ex);
}
}
}

Database Navigation Operations:-


1) INSERT operation:
To insert a new record into the table Users with following details:
o username: bill
o password: secretpass
o fullname: Bill Gates
o email: bill.gates@microsoft.com
Example:
String sql = "INSERT INTO Users (username, password, fullname, email) VALUES (?, ?, ?, ?)";
PreparedStatement statement = conn.prepareStatement(sql);
statement.setString(1, "bill");
statement.setString(2, "secretpass");
statement.setString(3, "Bill Gates");
statement.setString(4, "bill.gates@microsoft.com");

int rowsInserted = statement.executeUpdate();


if (rowsInserted > 0) {
System.out.println("A new user was inserted successfully!");
}

In this code, create a parameterized SQL INSERT statement and create a PreparedStatement from
the Connectionobject. To set values for the parameters in the INSERT statement, we use
the PreparedStatement‘s setString () methods because all these columns in the table Users are of type
VARCHAR which is translated to String type in Java. Note that the parameter index is 1-based (unlike
0-based index in Java array).
Finally call the PreparedStatement’s executeUpdate () method to execute the INSERT
statement. This method returns an update count indicating how many rows in the table were affected by
the query, so checking this return value is necessary to ensure the query was executed successfully. In
this case, executeUpdate () method should return 1 to indicate one record was inserted.

2) SELECT operation:
The following code snippet queries all records from the Users table and print out details for each
record:
String sql = "SELECT * FROM Users";

Statement statement = conn.createStatement();


ResultSet result = statement.executeQuery(sql);

int count = 0;

while (result.next()){
String name = result.getString(2);
Department of Computer Engineering 118
Database Management Systems Lab T.E (Computer Engineering)

String pass = result.getString(3);


String fullname = result.getString("fullname");
String email = result.getString("email");
String output = "User #%d: %s - %s - %s - %s";
System.out.println(String.format(output, ++count, name, pass, fullname, email));
}

The while loop iterates over the rows contained in the result set by repeatedly checking return value of
the ResultSet’s next() method. The next() method moves a cursor forward in the result set to check if
there is any remaining record. For each iteration, the result set contains data for the current row, and we
use the ResultSet’s getXXX(column index/column name) method to retrieve value of a specific column
in the current row.

3) UPDATE operation:
The following code snippet will update the record of “Bill Gates” as we inserted previously:
String sql = "UPDATE Users SET password=?, fullname=?, email=? WHERE username=?";

PreparedStatement statement = conn.prepareStatement(sql);


statement.setString(1, "123456789");
statement.setString(2, "William Henry Bill Gates");
statement.setString(3, "bill.gates@microsoft.com");
statement.setString(4, "bill");

int rowsUpdated = statement.executeUpdate();


if (rowsUpdated > 0) {
System.out.println("An existing user was updated successfully!");
}

4) DELETE operation:
The following code snippet will delete a record whose username field contains “bill”:

String sql = "DELETE FROM Users WHERE username=?";

PreparedStatement statement = conn.prepareStatement(sql);


statement.setString(1, "bill");

int rowsDeleted = statement.executeUpdate();


if (rowsDeleted > 0) {
System.out.println("A user was deleted successfully!");
}

Program:
Steps:
1. Open Eclipse
2. FileNewJava ProjectNextEnter project name: assign17nextFinish
3. If package explorer is invisible then follow the following steps:
Windowshow viewselect package Explorer (Can see project name)

Department of Computer Engineering 119


Database Management Systems Lab T.E (Computer Engineering)

4. Right click on project nameSelect new Class Give class name office(name of class should be the name of database
created in terminal)ok
5. Download mysql-connector-java.jar file
Procedure to add jar file:
1.In project explorer window right click on project nameSelect Build pathConfigure Build path(open the configuration
window automatically)select library tabclick on add external jar buttonselect mysql-connector-java.jar file.
6. Open terminalcreate database officecreate table student
7. Open eclipse (containing project) and enter below code in class file office
Office.java file (Create in Eclipse)

import java.sql.*;
public class office {

public static void main(String[] args)


{
try
{
Class.forName("com.mysql.jdbc.Driver"); //Driver Name
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/office","root","");
//Localhost-"servername",3306-port number,ab-database name
Statement stmt=con.createStatement();
ResultSet rs=stmt.executeQuery("select * from student");
while(rs.next())
System.out.println(rs.getInt(1)+" "+rs.getString(2));
con.close();
}
catch(Exception e)
{
System.out.println(e);
}
}

}
Output:

1 abc

2 def

Conclusion: Studied JDBC, types of JDBC Drivers and performed MySQL database connectivity with
Java and also performed database navigation operations.

Department of Computer Engineering 120


1

Potrebbero piacerti anche