DBMS - Lab Manual 2023-24
DBMS - Lab Manual 2023-24
(A.Y. 2024-25)
Class: TE
Name of student:
Index
Conducted Submission
Sr. Title Date Date/Sign
No.
Propose a Conceptual Design using ER features using tools
like ERD plus, ER Win etc. Convert the ER diagram into
1 tables on paper and propose a normalize Relational data
model.
Write SQL queries using Insert, Select, Update, delete with
operators, functions, and set operator etc. Use of SQL
2 objects such as Table, View, Index, Sequence, Synonym,
different constraints etc.
Write SQL queries using Insert, Select, Update, delete with
operators, functions, and set operator etc. Use of SQL
3 objects such as Table, View, Index, Sequence, Synonym,
different constraints etc.
Write the SQL queries using of concepts like all types of
4 Join, Sub- Query and View
Write the SQL queries using of concepts like all types of
5 Join, Sub- Query and View
Write a Unnamed PL/SQL code block for given
6 requirements (use of Control structure and Exception
handling is mandatory)
Write a Named PL/SQL Block for given requirements
7 using PL/SQL Stored Procedure and Stored Function.
Write a Named PL/SQL Block for given requirements
8 using PL/SQL Stored Procedure and Stored Function.
Write a PL/SQL code block using Cursors (All types:
9 Implicit, Explicit, Cursor FOR Loop, Parameterized Cursor)
Write a PL/SQL code block using Cursors (All types:
10 Implicit, Explicit, Cursor FOR Loop, Parameterized
Cursor)
Write a PL/SQL Code block using Database Trigger (All
11 Types: Row level and Statement level triggers, Before and
After Triggers).
Write a PL/SQL Code block using Database Trigger (All
12 Types: Row level and Statement level triggers, Before and
After Triggers).
Write a program to implement MYSQL/Oracle database
connectivity with any front-end language to implement
13 Database navigation operations (add, delete, edit etc)
Assignment Name: - Propose a Conceptual Design using ER features using tools like ERD plus, ER
Win etc. (Identifying entities, relationships between entities, attributes, keys, cardinalities,
generalization, specialization etc.) Convert the ER diagram into relational tables and normalize
Relational data model.
Theory: -
Objective:
To learn and understand the concept offer Model and steps to Design ER Model and to ER
Model into table.
New Concepts:
Entity-Relationship model is used in the conceptual design of a database ( ☞ conceptual level,
conceptual schema). A database schema in the ER model can be represented pictorially (Entity-
Relationship diagram)
Components of ER Diagram:
1> Entity: real-world object or thing with an independent existence and which is distinguishable
from other objects. An entity is an object or component of data. An entity is represented as rectangle
in an ER diagram.
Examples are a person, car, customer, product, gene, book etc.
2> Attributes: an entity is represented by a set of attributes . An attribute describes the property of
an entity. e.g., name, age, salary, price etc. Attribute values that describe each entity become a major
part of the data eventually stored in a database.
An attribute is represented as Oval in an ER diagram. There are four types of attributes:
1. Key attribute
2. Composite attribute
3. Multivalued attribute
4. Derived attribute
1. Key attribute:
ER diagram key attribute: A key attribute can uniquely identify an entity from an entity set. For
example, student roll number can uniquely identify a student from a set of students. Key attribute is
represented by oval same as other attributes however the text of key attribute is underlined.
2. Composite attribute:
ER diagram composite attribute: An attribute that is a combination of other attributes is known as
composite attribute. For example, In student entity, the student address is a composite attribute as
an address is composed of other attributes such as pin code, state, country.
3. Multivalued attribute:
An attribute that can hold multiple values is known as multivalued attribute. It is represented with
double ovals in an ER Diagram. For example – A person can have more than one phone numbers so
the phone number attribute is multivalued.
4. Derived attribute:
A derived attribute is one whose value is dynamic and derived from another attribute. It is
represented by dashed oval in an ER Diagram. For example – Person age is a derived attribute as it
changes over time and can be derived from another attribute (Date of birth).
3> Relationship
A relationship is represented by diamond shape in ER diagram, it shows the relationship
among entities. There are four types of relationships:
1. One to One
2. One to Many
3. Many to One
4. Many to Many
Many-To-Many (default)
Meaning: An employee can work in many departments (≥ 0),and a department can have
several employees
Many-To-One
Meaning: An employee can work in at most one department (≤ 1), and a department can have
several employees.
One-To-Many
Meaning: An employee can work in many departments (≥ 0), but a department can have at
most one employee.
One-To-One
Meaning: An employee can work in at most one department, and a department can have at
most one employee.
Specialization
• Process of defining a set of subclasses of an entity type (top-down)
HOURLY EMPS is a subclass of EMPLOYEES and thus inherits its attributes and relationships
(same for CONTRACT EMPS).
Generalization:
• Reverse process of specialization (bottom-up); identify common features of entity types and
generalize them into single superclass (including primary key!)
ERD Plus: A database modeling tool for creating Entity Relationship Diagrams, Relational
Schemas, Star Schemas, and SQL DDL statements.
https://erdplus.com/standalone
Assignment Name: - Design and Develop SQL DDL statements which demonstrate the use
of SQL objects such as Table, View, Index, Sequence, Synonym, different constraints etc.
Theory: -
Objective:
● To learn and understand the concept and DDL queries of SQL Table,View
and Index using MYSQL using 2-tier .
New Concepts:
CREATE Table
VARCHAR is a good choice for the name, owner, and species columns because the column values
vary in length. The lengths in those column definitions need not all be the same, and need not be
20. You can normally pick any length from 1 to 65535, whatever seems most reasonable to you.
DESCRIBE Table
To verify that your table was created the way you expected, use a DESCRIBE statement:
+ + + + + + +
| Field | Type | Null | Key | Default | Extra |
+ + + + + + +
| roll_no | int (3) | NO | PRI | NULL | auto_increment |
| name | varchar(20) | NO | | NULL | |
| age | int(3) | NO | | NULL | |
+ + + + + + +
Constraints
You can also add constraint after table creation using alter table option
Eg Alter table stud add constraint prk1 primary key(rollno);
You can also drop constraint using Drop command & name of constraint
Eg Drop constraint prk1;
ALTER Table
The ALTER TABLE statement is used to add, delete, or modify columns in an existing table
Syntax
Example
Following example shows use of Alter command. First example add new column Address in table
and second example modify in size of age column. Third example shows how to drop column age.
DROP Table
What if we only want to delete the data inside the table, and not the table itself?
VIEW in MySQL
CREATE VIEW Statement
In SQL, a view is a virtual table based on the result-set of an SQL statement. A view contains
rows and columns, just like a real table. The fields in a view are fields from one or more real
tables in the database.
INDEX in MySQL
Index in SQL is created on existing tables to retrieve the rows quickly. When there are thousands
of records in a table, retrieving information will take a long time. Therefore indexes are created on
columns which are accessed frequently, so that the information can be retrieved quickly. Indexes
can be created on a single column or a group of columns. When a index is created, it first sorts the
data and then it assigns a ROWID for each row.
Drop Index
Assignment Name: - Write at least 10 SQL queries on the suitable database application
using SQL DML statements.
Theory: -
Objective:
To learn and understand the DML queries of SQL using MYSQL
New Concepts:
SQL Wildcards
SQL wildcards can substitute for one or more characters when searching for data in a database.
SQL wildcards must be used with the SQL LIKE operator.
Wildcard Description
Example:
LastName
Savita
Sarika
In a table, some of the columns may contain duplicate values. This is not a problem, however,
sometimes you will want to list only the different (distinct) values in a table.
The DISTINCT keyword can be used to return only distinct (different) values.
Address
Pune
Bombay
SQL IN Syntax
SELECT column_name(s) FROM table_name
WHERE column_name IN (value1,value2,...)
IN Operator Example
Now we want to select the persons with a last name equal to "Hansen" or "Pettersen" from the
table above.
If you leave out the WHERE clause you get all the tuples in the specified tables.
Use '*' as the attribute list to specify all the attributes of the specified tables.
SELECT * FROM table_name ;
SQL aggregate functions return a single value, calculated from values in a column.
Useful aggregate functions:
The COUNT(column_name) function returns the number of values (NULL values will not be
counted) of the specified column:
This clause allows the rows of a table to be grouped by the value of some attribute(s); the
SELECT clause is applied to each group: The GROUP BY statement is used in conjunction with
the aggregate functions to group the result-set by one or more columns.
Now we want to find the total sum (total order) of each customer.
Customer SUM(OrderPrice)
Hansen 2000
Nilsen 1700
Jensen 2000
The HAVING clause was added to SQL because the WHERE keyword could not be used with
aggregate functions.
Now we want to find if any of the customers have a total order of less than 2000.
Customer SUM(OrderPrice)
Nilsen 1700
Group A: Assignment No 3
Title of Assignment: SQL Queries – all types of Join, Sub-Query and View:
Assignment Name: - Design at least 10 SQL queries for suitable database application using
SQL DML statements: all types of Join, Sub-Query and View.
Theory: -
Objective:
To learn and understand the concept and queries of SQL joints using MYSQL
. To learn and understand the concept and queries of SQL Sun-Queries and joins
using MYSQL
New Concepts:
Introduction to Joins: An SQL JOIN clause is used to combine rows from two or more tables, based
on a common field between them. Before we continue with examples, we will list the types of JOIN
you can use, and the differences between them.
JOIN: Return rows when there is at least one match in both tables
LEFT JOIN: Return all rows from the left table, even if there are no matches in the right
table
RIGHT JOIN: Return all rows from the right table, even if there are no matches in the left
table
FULL JOIN: Return rows when there is a match in one of the tables
SELECT column_name(s)
FROM table_name1,table_name2
WHERE table_name1.column_name=table_name2.column_name
The LEFT JOIN keyword returns all rows from the left table (table_name1), even if there are no
matches in the right table (table_name2).
The LEFT JOIN keyword returns all the rows from the left table (Persons), even if there are no
matches in the right table (Orders).
The RIGHT JOIN keyword Return all rows from the right table (table_name2), even if there are no
matches in the left table (table_name1).
SQL RIGHT JOIN EXAMPLE: Now we want to list all the orders with containing persons - if any,
from the tables above.
The RIGHT JOIN keyword returns all the rows from the right table (Orders), even if there are no
matches in the left table (Persons).
SQL FULL JOIN KEYWORD
The FULL JOIN keyword return rows when there is a match in one of the tables.
SQL FULL JOIN Syntax
SELECT column_name(s)
FROM table_name1
FULL JOIN table_name2
ON table_name1.column_name=table_name2.column_name
Types of Subqueries
Single Row Sub Query: Sub query which returns single row output. They mark the usage of single
row comparison operators, when used in WHERE conditions.
Multiple row sub query: Sub query returning multiple row output. They make use of multiple row
comparison operators like IN, ANY, ALL. There can be sub queries returning multiple columns also.
Correlated Sub Query: Correlated subqueries depend on data provided by the outer
query.Thistype of subquery also includes subqueries that use the EXISTS operator to test the
existence of data rows satisfying specified criteria.
Example:
Display the information of employees, paid more than ‘pooja' from emptable
Select *from emp where salary > (select salaryfrom empwhere name=‘Pooja’) ;
[> ALL] More than the highest value returned by the subquery
[< ALL] Less than the lowest value returned by the subquery
[< ANY] Less than the highest value returned by the subquery
[> ANY] More than the lowest value returned by the subquery
[= ANY] Equal to any value returned by the subquery (same as IN)
>All Example-
Display the employee name, salary and department no of those employees whose salary is
higher than all developers’ salary.
SELECT Ename, salary, deptnoFROM EMPWHERE salary > All ( SELECT salaryFROM empWhere
post=‘Developer’)
Group A: Assignment No 4 & 5
Assignment Name: - 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(Roll_no, Name, Date_of_Issue, 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 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.
OR
Write a PL/SQL code block to calculate the area of a circle for a value of radius varying from 5 to 9.
Store the radius and the corresponding values of calculated area in an empty table named areas,
consisting of two columns, radius and area.
Theory: -
PL/SQL Introduction
•PL/SQL is a combination of SQL along with the procedural features of programming languages
•Basic Syntax of PL/SQL which is a block-structured language; this means that the PL/SQL
programs are divided and written in logical blocks of code. Each block consists of three sub-
parts
Anonymous blocks are PL/SQL blocks which do not have any names assigned to them.
They need to be created and used in the same session because they will not be stored in the
server as a database objects.
Since they need not to store in the database, they need no compilation steps.
They are written and executed directly, and compilation and execution happen in a single
process.
Named blocks:
Named blocks are having a specific and unique name for them.They are stored as the database
objects in the server. Since they are available as database objects, they can be referred to or used
as long as it is present in the server.
1. Procedure
2. Function
Begin<Declare variable_namedata_type;>
<Control Statements/loops>
End
Stored Procedure-Parameters
IN –is the default mode. When you define an IN parameter in a stored procedure, the calling program has
to pass an argument to the stored procedure.
OUT –the value of an OUT parameter can be changed inside the stored procedure and its new value is
passed back to the calling program
INOUT –an INOUT parameter is the combination of IN and OUT parameters. It means that the calling
program may pass the argument, and the stored procedure can modify the INOUT parameter and pass the
new value back to the calling program.
Mysql> DELIMITER //
Mysql> CREATE PROCEDURE Allstud(IN SNameVARCHAR(25))
BEGIN
SELECT *FROM stud where Name=SName;
END
//
Mysql> DELIMITER ;
Mysql> call Allstud(‘Reena’);
The IN and OUT parameter example
Mysql> CREATE PROCEDURE Allstud(IN Rno1 int,OUT SName VARCHAR)
BEGIN
SELECT Name into SName FROM stud where Rno=RNo1;
END
//
Mysql> call Allstud(2,@SName)//
Mysql> select @Sname
Date Related Functions required to solve the assignment
CURDATE() -•The CURDATE() function returns the current date.
Note:This function returns the current date as a "YYYY-MM-DD" format
•Example
•Return current date:
•SELECT CURDATE();
DATEDIFF()
The DATEDIFF() function returns the difference in days between two date values.
•Syntax
•DATEDIFF(date1, date2)
•Example
•Return the difference in days between two date values:
•SELECT DATEDIFF("2017-06-25", "2017-06-15");
Exception handling
Declaring a handler
•To declare a handler, you use thestatement as follows:
•DECLARE action HANDLER FOR condition_value statement;
• If a condition whose value matches the condition_value, MySQL will execute the statement and continue
or exit the current code block based on the action .
•The action accepts one of the following values:
1. CONTINUE :the execution of the enclosing code block ( BEGIN ... END ) continues.
2. EXIT : the execution of the enclosing code block, where the handler is declared, terminates.
Group A: Assignment No : 6
Assignment Name: -.
Write a Stored Function 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)
Theory: -
If procedural programming is new to you, you may be wondering what the difference is between a
Stored Procedure and a Stored Function. Not too much really.
A function always returns a result, and can be called inside an SQL statement just like ordinary SQL
functions.
A function parameter is the equivalent of the IN procedure parameter, as functions use the RETURN
keyword to determine what is passed back.
Stored functions also have slightly more limitations in what SQL statements they can run than
stored procedures.
A standalone function is created using the CREATE FUNCTION statement. The simplified syntax for
the CREATE OR REPLACE PROCEDURE statement is as follows −
CREATE [OR REPLACE] FUNCTION function_name
[(parameter_name [IN | OUT | IN OUT] type [, ...])]
RETURNS return_datatype
BEGIN
< function_body >
END;
Where,
function-name specifies the name of the function.
[OR REPLACE] option allows the modification of an existing function.
The optional parameter list contains name, mode and types of the parameters. IN represents
the value that will be passed from outside and OUT represents the parameter that will be
used to return a value outside of the procedure.
The function must contain a return statement.
The RETURNS clause specifies the data type you are going to return from the function.
function-body contains the executable part.
Begin
Declare int;
Set c= a+b;
Return c;
End;
//
MySQL> Select Add1(10,20) ; To run the Function
Example 2: Take rollno as input from user and pass to function, Function will return name of
student belonging to that rollno.
Begin
Declare sname varchar(20);
Select name into sname from Stud where rno=rno1;
Return sname;
End;
//
MySQL> Select Rname(1) ; To run the Function
Title of Assignment: Cursors: (All types: Implicit, Explicit, Cursor FOR Loop, Parameterized
Cursor)
Assignment Name: - 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.
Theory: -
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.
To handle a result set inside a stored procedure, you use a cursor. A cursor allows you to iterate a
set of rows returned by a query and process each row accordingly.
Types of Cursor
1>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. Implicit Cursor is associated with following DML Statements INSERT,
UPDATE , DELETE
2>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.
Working with an explicit cursor includes the following steps
Read only: you cannot update data in the underlying table through the cursor
Non-scrollable: you can only fetch rows in the order determined by the SELECT statement. You
cannot fetch rows in the reversed order. In addition, you cannot skip rows or jump to a specific row
in the result set
Asensitive: there are two kinds of cursors: asensitive cursor and insensitive cursor. An asensitive
cursor points to the actual data, whereas an insensitive cursor uses a temporary copy of the data. An
asensitive cursor performs faster than an insensitive cursor because it does not have to make a
temporary copy of data.
1. DECLARE statement: The cursor declaration must be after any variable declaration. •A
cursor must always be associated with a SELECT statement
Syntax
2. OPEN statement: The OPEN statement initializes the result set for the cursor, therefore,
you must call the OPEN statement before fetching rows from the result set.
Syntax
OPEN cursor_name;
3. LOOP statement: The LOOP depends on the careful placement of the LEAVE statement to
terminate iteration.
Syntax
[label_name:]
LOOPstatement_list
END LOOP [label_name]
4. FETCH statement: Then, you 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.
Syntax
5. CLOSE statement: Finally, you call the CLOSE statement to deactivate the cursor and
release the memory associated with it
Syntax
CLOSE cursor_name;
When working with MySQL cursor, you must also declare a NOT FOUND handler to handle
the situation when the cursor could not find any row. Because each time you 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.
Syntax
Cursor Example 1:
DECLARE id VARCHAR(3);
DECLARE name1 VARCHAR(20);
-- this flag will be set to true when cursor reaches end of table
DECLARE exit_loop BOOLEAN;
-- Declare the cursor
DECLARE c1 CURSOR FOR SELECT rno, name FROM stud;
-- start looping
L1: LOOP
-- read the id and name from next row into the variables
FETCH c1 INTO id, name1;
select id,name1;
-- check if the exit_loop flag has been set by mysql, close the cursor and exit the loop if it
has.
IF exit_loop THEN
CLOSE c1;
LEAVE L1;
END IF;
END LOOP L1;
END
Assignment to be performed:
• 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.
Group A: Assignment No : 8
Title of Assignment: Database Trigger (All Types: Row level and Statement level triggers, Before
and After Triggers).
Assignment Name: -.
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.
Theory: -
A trigger in MySQL is a set of SQL statements that reside in a system catalog. It is a special type of
stored procedure that is invoked automatically in response to an event. Each trigger is associated with
a table, which is activated on any DML statement such as INSERT, UPDATE, or DELETE.
A trigger is called a special procedure because it cannot be called directly like a stored procedure.
The main difference between the trigger and procedure is that a trigger is called automatically when
a data modification event is made against a table. In contrast, a stored procedure must be called
explicitly.
Generally, triggers are of two types according to the SQL standard: row-level triggers and statement-
level triggers.
Row-Level Trigger: It is a trigger, which is activated for each row by a triggering statement such as
insert, update, or delete. For example, if a table has inserted, updated, or deleted multiple rows, the
row trigger is fired automatically for each row affected by the insert, update, or delete statement.
Statement-Level Trigger: It is a trigger, which is fired once for each event that occurs on a table
regardless of how many rows are inserted, updated, or deleted.
We can define the maximum six types of actions or events in the form of triggers:
1. Before Insert: It is activated before the insertion of data into the table.
2. After Insert: It is activated after the insertion of data into the table.
3. Before Update: It is activated before the update of data in the table.
4. After Update: It is activated after the update of the data in the table.
5. Before Delete: It is activated before the data is removed from the table.
6. After Delete: It is activated after the deletion of data from the table.
When we use a statement that does not use INSERT, UPDATE or DELETE query to change the data in
a table, the triggers associated with the trigger will not be invoked.
Trigger Syntax
We can use the CREATE TRIGGER statement for creating a new trigger in MySQL. Below is the
syntax of creating a trigger in MySQL:
The trigger body can access the column's values, which are affected by the DML statement. The
NEW and OLD modifiers are used to distinguish the column values BEFORE and AFTER the execution
of the DML statement. We can use the column name with NEW and OLD modifiers as
OLD.col_name and NEW.col_name. The OLD.column_name indicates the column of an existing row
before the updation or deletion occurs. NEW.col_name indicates the column of a new row that will be
inserted or an existing row after it is updated.
Trigger Example:
Create two tables emp and emp_update as shown below
• Create table emp(EmpNo INT, Lname VARCHAR(50), Salary int(5));
• Create table emp_audit (EmpNo INT, Lname VARCHAR(50), changedat DATETIME, action
VARCHAR(50));
MySQL>DELIMITER //
MySQL>CREATE TRIGGER t1
AFTER UPDATE ON emp
FOR EACH ROW
BEGIN
INSERT INTO emp_audit
SET EmpNo = OLD. EmpNo,
Lname= OLD.Lname,
changedat = NOW()
action = 'update';
END
//
MySQL>DELIMITER ;
MySQL>SHOW TRIGGERS; // To see information about triggers
Assignment to Performed:
• 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.
Group A: Assignment No : 9
Theory: -
• Eclipse
• JDK 1.6
• MySQL
• Java-MySQL Connector
The interface for accessing relational databases from Java is Java Database Connectivity
(JDBC). Via JDBC you create a connection to the database, issue database queries and
update as well as receive the results.
JDBC provides an interface which allows you to perform SQL operations independently of
the instance of the used database. To use JDBC, you require the database specific
implementation of the JDBC driver.
To connect to MySQL from Java, you have to use the JDBC driver from MySQL. The MySQL
JDBC driver is called MySQL Connector/J. You find the latest MySQL JDBC driver under the
following URL: http://dev.mysql.com/downloads/connector/j.
To connect Java application with the MySQL database, we need to follow following
steps.
1. Driver class: The driver class for the mysql database is com.mysql.jdbc.Driver.
2. Connection URL: The connection URL for the mysql database
is jdbc:mysql://localhost:3306/db1 where jdbc is the API, mysql is the database,
localhost is the server name on which mysql is running, we may also use IP address,
3306 is the port number and sonoo is the database name. We may use any database,
in such case, we need to replace the db1 with our database name.
3. Username: The default username for the mysql database is root.
4. Password: It is the password given by the user at the time of installing the mysql
database.
2. Load Driver
Class.forName("oracle.jdbc.driver.OracleDriver");
3. Create connection
Connection con = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/DatabaseName","username","passwd ")
ResultSet rs = stmt.executeQuery(sql1);
//executeQuery used to run the select query and store the result in ResultSet
7. Close connection
• stmt.close();
• con.close();
Group B: Assignment No : 1
Assignment Name: -.
Design and Develop MongoDB Queries using CRUD operations. (Use CRUD operations, SAVE
method, logical operators)
Theory: -
What is NoSQL?
NoSQL is a non-relational DBMS, that does not require a fixed schema, avoids joins, and is easy to
scale. The purpose of using a NoSQL database is for distributed data stores with humongous data
storage needs. NoSQL is used for Big data and real-time web apps. For example, companies like
Twitter, Facebook, Google collect terabytes of user data every single day.
NoSQL database stands for "Not Only SQL" or "Not SQL." Though a better term would be "NoREL",
NoSQL caught on. Carl Strozz introduced the NoSQL concept in 1998.
Why NoSQL?
The concept of NoSQL databases became popular with Internet giants like Google, Facebook,
Amazon, etc. who deal with huge volumes of data. The system response time becomes slow when
you use RDBMS for massive volumes of data.
To resolve this problem, we could "scale up" our systems by upgrading our existing hardware. This
process is expensive.
MongoDB
Advantages of MongoDB
• Schema less : Number of fields, content and size of the document can be differ from one
document to another.
• No complex joins
RDBMS MongoDB
Database Database
Column Field
Index Index
Partition Shard
• String : This is most commonly used datatype to store the data. String in mongodb must be
UTF-8 valid.
• Integer : This type is used to store a numerical value. Integer can be 32 bit or 64 bit
depending upon your server.
• Boolean : This type is used to store a boolean (true/ false) value.
• Double : This type is used to store floating point values.
• Min/ Max keys : This type is used to compare a value against the lowest and highest BSON
elements.
• Arrays : This type is used to store arrays or list or multiple values into one key.
• Timestamp : ctimestamp. This can be handy for recording when a document has been
modified or added.
• Object : This datatype is used for embedded documents.
• Null : This type is used to store a Null value.
• Symbol : This datatype is used identically to a string however, it's generally reserved for
languages that use a specific symbol type.
• Date : This datatype is used to store the current date or time in UNIX time format. You can
specify your own date time by creating object of Date and passing day, month, year into it.
• Object ID : This datatype is used to store the document’s ID.
• Binary data : This datatype is used to store binay data.
• Code : This datatype is used to store javascript code into document.
• Regular expression : This datatype is used to store regular expression
• db.createCollection (name)
• Ex:- db.createCollection(Stud)
• To create collection
• >show collections
• db.databasename.insert
• ({Key : Value})
• Ex:- db.Stud.insert({{Name:”Jiya”})
CRUD Operations:
• Insert
• Find
• Update
• Delete
The insert() Method:- To insert data into MongoDB collection, you need to use MongoDB's insert()
or save()method.
Syntax
>db.COLLECTION_NAME.insert(document)
Example
_id Field
• If the document does not specify an _id field, then MongoDB will add the _id field and assign
a unique ObjectId for the document before inserting.
• The _id value must be unique within the collection to avoid duplicate key error.
Insert a Document without Specifying an _id Field
• db.stud.insert( { Name : “Reena", Rno: 15 } )
• db.stud.find()
{ "_id" : "5063114bd386d8fadbd6b004”, “Name” : “Reena", “Rno”: 15 }
Insert a Document Specifying an _id Field
• db.stud.insert({ _id: 10, Name : “Reena", Rno: 15 } )
• db.stud.find()
{ "_id" : 10, “Name” : “Reena", “Rno”: 15 }
Insert Single Documents
db.stud.insert ( {Name: “Ankit”, Rno:1, Address: “Pune”} )
The pretty() Method- To display the results in a formatted way, you can use pretty() method.
Syntax
>db. COLLECTION_NAME.find().pretty()
Specify Equality Condition
use the query document { <field>: <value> }
Examples:
• db.stud.find( name: “Jiya" } )
• db.stud.find( { _id: 5 } )
Comparison Operators
Operator Description
$eq Matches values that are equal to a specified value.
$gt Matches values that are greater than a specified value.
• db.stud.find().count()
Returns no of documents in the collection
Syntax
db.CollectionName.update (
<query/Condition>,
<update with $set or $unset>,
{
upsert: <boolean>,
multi: <boolean>,
})
upsert
• If set to True, creates new document if no matches found.
multi
• If set to True, updates multiple documents that matches the query criteria
db.stud.update(
{ _id: 100 },
{ age: 25})
2> Set age = 25 where id is 100, Only the age field of one document is updated where condition
is matched .
db.stud.update(
{ _id: 100 },
{ $set:{age: 25}})
db.stud.update(
{ _id: 100 },
{ $unset:{age: 1}})
Assignment Name: -. Design & Develop MongoDB Queries using Aggregation and Indexing
with suitable example using MongoDB
Theory: -
Indexing Types
Single field index only includes data from a single field of the Single Field Indexes
documents in a collection.
Compound index includes more than one field of the documents in Compound Indexes a
collection.
Multikey index is an index on an array field, adding an index key for Multikey each value in
the array. Indexes
Geospatial indexes support location-based searches. Geospatial Indexes and Queries Text
Indexes
Text indexes support search of string content in documents.
Hashed Index -Hashed indexes maintain entries with hashes of the values of the indexed
field and are used with sharded clusters to support hashed shard keys.
Index Properties:
Index Properties -The properties you can specify when building indexes.
1. TTL Indexes The TTL index is used for TTL collections, which expire data after a period of
time
2. Unique Indexes A unique index causes MongoDB to reject all documents that contain a
duplicate value for the indexed field.
3. Sparse Indexes A sparse index does not index documents that do not have the indexed field.
Index Creation:
Syntax:
db.collection.getIndexes()
Returns an array that holds a list of documents that identify and describe the existing indexes on
the collection.
Index Drop
Syntax:
1. db.collection.dropIndex()
2. db.collection.dropIndex(index)
Example:
1. db.stud.dropIndex()
2. db.stud.dropIndex( { “name" : 1 } )
db.records.createIndex( { name: 1 } )
This index can support an ascending sort on name :
db.records.find().sort( { name: 1 } )
The index can also support descending sort
db.records.find().sort( { a: -1 } )
db.stud.findOne( {rno:2} ), using index {rno:1}
Aggregation:
Aggregation operations group values from multiple documents together, and can perform a variety of
operations on the grouped data
Syntax:
• >db.COLLECTION_NAME.aggregate(AGGREGATE_OPERATION)
aggregate() method
Possible stages in aggregation
Title of Assignment: Implement Map reduce operation with suitable example using
MongoDB.
Theory: -
Map-Reduce
large volumes of data into useful aggregated results. For mapreduce operations, MongoDB
provides the mapReduce database command.
MapReduce:
Map-Reduce:
In very simple terms, the mapReduce command takes 2 primary inputs, the mapper function and
the reducer function.
A Mapper will start off by reading a collection of data and building a Map with only the required
fields we wish to process and group them into one array based on the key.
And then this key value pair is fed into a Reducer, which will process the values.
Map-Reduce Syntax:
db.collection.mapReduce(
function() {emit(key, value);},
function(key,values) {return reduceFunction},
{
out: collection,
query: document,
sort: document,
limit: number
}
)
Map-Reduce Syntax Explanation:
The above map-reduce function will query the collection, and then map
reduced based on the keys that have multiple values. Here, we have
documents.
Theory: -
• Eclipse
• JDK 1.6
• MongoDB
• MongoDB-Java-Driver
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
1. Import packages
import com.mongodb.*;
2. Create connection
3. Create Database
DB db = mongo.getDB("database name");
4. Insert Document
coll.insert(d1);
5. Display document
while (cursor.hasNext())
System.out.println(cursor.next());
6. Update Document
• query.put("name", “Monika");
• newDocument.put("name", “Ragini");
• updateObj.put("$set", newDocument);
• Coll.update(query, updateObj);
7. Remove document
Coll.remove(searchQuery);