0% found this document useful (0 votes)
26 views

Dbmslabmanual

The document discusses installing and setting up the MySQL database on Ubuntu. It provides hardware and software requirements and outlines the basic concepts of MySQL including what it is, that it is a relational database system, and how SQL is used.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
26 views

Dbmslabmanual

The document discusses installing and setting up the MySQL database on Ubuntu. It provides hardware and software requirements and outlines the basic concepts of MySQL including what it is, that it is a relational database system, and how SQL is used.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 127

Bharati Vidyapeeth's College of Engineering for Women

Computer Engineering
Class: T.E. Computer Engineering
Subject: Database Management System Lab (310247)
2015 Pattern

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

Semester I

DBMS LAB MANUAL

Prepared by:- Prof.Shital B. Jadhav


About Savitribai Phule Pune University

Savitribai Phule Pune University, one of the premier universities in India, is positioned in the
North-western part of Pune city. It occupies an area of about 411 acres. It was established on
10th February, 1949 under the Poona University Act. The university houses 46 academic
departments. It is popularly known as the 'Oxford of the East'. It has about 307 recognized
research institutes and 612 affiliated colleges offering graduate and under-graduate courses. The
university attracts many foreign students due to its excellent facilities. It offers good
accommodation facility. There is a provision of hostel for the students. There is a well-stocked
library containing plenty of books regarding various subjects. The university offers different
scholarships to the students. The university conducts seminars and conferences for the students.

About College

Bharati Vidyapeeth’s College of Engineering for Women was established in June 2000, with the
collective efforts of experts having long and outstanding academic experience in the field of
professional education with the mission 'Social transformation through dynamic education.'

Vision:
Women Empowerment through Technical Education.

Mission:
Develop women students to rise to their full potential.
Impart knowledge and prepare competent engineers.

About Course
A database-management system (DBMS) is a computer-software application that interacts
with end-users, other applications, and the database itself to capture and analyze data. A general-
purpose DBMS allows the definition, creation, querying, update, and administration of
databases. A database is generally stored in a DBMS-specific format which is not portable, but
different DBMSs can share data by using standards such as SQL and ODBC or JDBC.
Computer scientists may classify database-management systems according to the database
models that they support. Relational databasesbecame dominant in the 1980s. These model data
as rows and columns in a series of tables, and the vast majority use SQL for writing and querying
data. In the 2000s, non-relational databases became popular, referred to as NoSQL because they
use different query languages.
Course Objectives

• To develop basic, intermediate and advanced Database programming skills


• To develop basic Database administration skills
• To percept transaction processing
Course Outcomes:
On completion of the course, student will be able to–
• Develop the ability to handle databases of varying complexities
• Use advanced database Programming concepts

Expt.No. Assignments Group A


1 Study of Open Source Relational Databases : MySQL
2 Design and Develop SQL DDL statements which demonstrate the use of SQL
objects such as Table, View, Index, Sequence, Synonym
3 Design at least 10 SQL queries for suitable database application using SQL DML
statements: Insert, Select, Update, Delete with operators, functions, and set
operator.
4 Design at least 10 SQL queries for suitable database application using SQL DML
statements: all types of Join, Sub-Query and View.
5 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 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.
6 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.
7 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.
8 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.
Assignments Group B
1 Study of Open Source NOSQL Database: MongoDB (Installation, Basic CRUD
operations, Execution)
2 Design and Develop MongoDB Queries using CRUD operations. (Use CRUD
operations, SAVE 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
Assignment Group C
1 Write a program to implement MogoDB database connectivity with PHP/
python/Java Implement Database navigation operations (add, delete, edit etc. )
using ODBC/JDBC.
2 Implement MYSQL/Oracle database connectivity with PHP/ python/Java
Implement Database navigation operations (add, delete, edit,) using
ODBC/JDBC.
3 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
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
GROUP A

EXPERIMENT 1

OBJECTIVE : To understand fundamental and to learn Installation of Mysql.

PROBLEM STATEMENT: Study of Open Source Relational Databases : MySQL

HARDWARE REQUIREMENT :

2 GHz dual core processor.


2 GiB RAM (system memory)
25 GB of hard-drive space (or USB stick, memory card or external drive but see LiveCD for an
alternative approach)

SOFTWARE REQUIREMENT :
Operating System- Ubuntu 16.04
Database- Mysql

OUTCOME : After completion of Assignment students are able to install Mysql database

THEORY:
What is MySQL?
MySQL, the most popular Open Source SQL database management system, is developed,
distributed, and supported by Oracle Corporation.
The MySQL Web site (http://www.mysql.com/) provides the latest information about MySQL
software.
• MySQL is a database management system.
A database is a structured collection of data. It may be anything from a simple shopping list to a
picture gallery or the vast amounts of information in a corporate network. To add, access, and
process data stored in a computer database, you need a database management system such as
MySQL Server. Since computers are very good at handling large amounts of data, database
management systems play a central role in computing, as standalone utilities, or as parts of other
applications.
• MySQL databases are relational.
A relational database stores data in separate tables rather than putting all the data in one big
storeroom. The database structures are organized into physical files optimized for speed. The
logical model, with objects such as databases, tables, views, rows, and columns, offers a flexible
programming environment. You set up rules governing the relationships between different data
fields, such as one-to-one, one-to-many, unique, required or optional, and “pointers” between
different tables. The database enforces these rules, so that with a well-designed database, your
application never sees inconsistent, duplicate, orphan, out-of-date, or missing data.
The SQL part of “MySQL” stands for “Structured Query Language”. SQL is the most common
standardized language used to access databases. Depending on your programming environment,
you might enter SQL directly (for example, to generate reports), embed SQL statements into
code written in another language, or use a language-specific API that hides the SQL syntax.
SQL is defined by the ANSI/ISO SQL Standard. The SQL standard has been evolving since
1986 and several versions exist. In this manual, “SQL-92” refers to the standard released in
1992, “SQL:1999” refers to the standard released in 1999, and “SQL:2003”refers to the current
version of the standard. We use the phrase “the SQL standard” to mean the current version of the
SQL Standard at any time.
• MySQL software is Open Source.
Open Source means that it is possible for anyone to use and modify the software. Anybody can
download the MySQL software from the Internet and use it without paying anything. If you
wish, you may study the source code and change it to suit your needs. The MySQL software uses
the GPL (GNU General Public License), http://www.fsf.org/licenses/, to define what you may
and may not do with the software in different situations. If you feel uncomfortable with the GPL
or need to embed MySQL code into a commercial application, you can buy a commercially
licensed version from us. See the MySQL Licensing Overview for more information
(http://www.mysql.com/company/legal/licensing/).
• The MySQL Database Server is very fast, reliable, scalable, and easy to use.
If that is what you are looking for, you should give it a try. MySQL Server can run comfortably
on a desktop or laptop, alongside your other applications, web servers, and so on, requiring little
or no attention. If you dedicate an entire machine to MySQL, you can adjust the settings to take
advantage of all the memory, CPU power, and I/O capacity available. MySQL can also scale up
to clusters of machines, networked together.
MySQL Server was originally developed to handle large databases much faster than existing
solutions and has been successfully used in highly demanding production environments for
several years. Although under constant development, MySQL Server today offers a rich and
useful set of functions. Its connectivity, speed, and security make MySQL Server highly suited
for accessing databases on the Internet.
• MySQL Server works in client/server or embedded systems.
The MySQL Database Software is a client/server system that consists of a multi-threaded SQL
server that supports different back ends, several different client programs and libraries,
administrative tools, and a wide range of application programming interfaces (APIs).
We also provide MySQL Server as an embedded multi-threaded library that you can link into
your application to get a smaller, faster, easier-to-manage standalone product.
• A large amount of contributed MySQL software is available.
MySQL Server has a practical set of features developed in close cooperation with our users. It is
very likely that your favorite application or language supports the MySQL Database Server.

The Main Features of MySQL


Internals and Portability
• Written in C and C++.
• Tested with a broad range of different compilers.
• Works on many different platforms. See
http://www.mysql.com/support/supportedplatforms/database.html.
• For portability, uses CMake in MySQL 5.5 and up. Previous series use GNU Automake,
Autoconf, and Libtool.
• Tested with Purify (a commercial memory leakage detector) as well as with Valgrind, a
GPL tool (http://developer.kde.org/~sewardj/).
• Uses multi-layered server design with independent modules.
• Designed to be fully multi-threaded using kernel threads, to easily use multiple CPUs if
they are available.
• Provides transactional and nontransactional storage engines.
• Uses very fast B-tree disk tables (MyISAM) with index compression.
• Designed to make it relatively easy to add other storage engines. This is useful if you
want to provide an SQL interface for an in-house database.
• Uses a very fast thread-based memory allocation system.
• Executes very fast joins using an optimized nested-loop join.
• Implements in-memory hash tables, which are used as temporary tables.
• Implements SQL functions using a highly optimized class library that should be as fast as
possible. Usually there is no memory allocation at all after query initialization.
• Provides the server as a separate program for use in a client/server networked
environment, and as a library that can be embedded (linked) into standalone applications. Such
applications can be used in isolation or in environments where no network is available.
Data Types
• Many data types: signed/unsigned integers 1, 2, 3, 4, and 8 bytes long, FLOAT,
DOUBLE, CHAR, VARCHAR, BINARY, VARBINARY, TEXT,BLOB, DATE, TIME,
DATETIME, TIMESTAMP, YEAR, SET, ENUM, and OpenGIS spatial types. See Chapter 11,
Data Types.
• Fixed-length and variable-length string types.
Statements and Functions
• Full operator and function support in the SELECT list and WHERE clause of queries. For
example:
• mysql> SELECT CONCAT(first_name, ' ', last_name)
• -> FROM citizen
-> WHERE income/dependents > 10000 AND age > 30;
• Full support for SQL GROUP BY and ORDER BY clauses. Support for group functions
(COUNT(), AVG(), STD(), SUM(), MAX(), MIN(), and GROUP_CONCAT()).
• Support for LEFT OUTER JOIN and RIGHT OUTER JOIN with both standard SQL and
ODBC syntax.
• Support for aliases on tables and columns as required by standard SQL.
• Support for DELETE, INSERT, REPLACE, and UPDATE to return the number of rows
that were changed (affected), or to return the number of rows matched instead by setting a flag
when connecting to the server.
• Support for MySQL-specific SHOW statements that retrieve information about
databases, storage engines, tables, and indexes. Support for the INFORMATION_SCHEMA
database, implemented according to standard SQL.
• An EXPLAIN statement to show how the optimizer resolves a query.
• Independence of function names from table or column names. For example, ABS is a
valid column name. The only restriction is that for a function call, no spaces are permitted
between the function name and the “(” that follows it. See Section 9.3, “Keywords and Reserved
Words”.
• You can refer to tables from different databases in the same statement.

Security
• A privilege and password system that is very flexible and secure, and that enables host-
based verification.
• Password security by encryption of all password traffic when you connect to a server.
Scalability and Limits
• Support for large databases. We use MySQL Server with databases that contain 50
million records. We also know of users who use MySQL Server with 200,000 tables and about
5,000,000,000 rows.
• Support for up to 64 indexes per table. Each index may consist of 1 to 16 columns or
parts of columns. The maximum index width for InnoDB tables is either 767 bytes or 3072 bytes.
See Section 14.8.1.7, “Limits on InnoDB Tables”. The maximum index width for MyISAM
tables is 1000 bytes. See Section 15.2, “The MyISAM Storage Engine”. An index may use a
prefix of a column for CHAR,VARCHAR, BLOB, or TEXT column types.

Connectivity
• Clients can connect to MySQL Server using several protocols:
• Clients can connect using TCP/IP sockets on any platform.
• On Windows systems, clients can connect using named pipes if the server is started with the -
-enable-named-pipe option. Windows servers also support shared-memory connections if
started with the --shared-memory option. Clients can connect through shared memory by
using the --protocol=memory option.
• On Unix systems, clients can connect using Unix domain socket files.
• MySQL client programs can be written in many languages. A client library written in C is
available for clients written in C or C++, or for any language that provides C bindings.
• APIs for C, C++, Eiffel, Java, Perl, PHP, Python, Ruby, and Tcl are available, enabling
MySQL clients to be written in many languages. See Chapter 27, Connectors and APIs.
• The Connector/ODBC (MyODBC) interface provides MySQL support for client programs that
use ODBC (Open Database Connectivity) connections. For example, you can use MS Access to
connect to your MySQL server. Clients can be run on Windows or Unix. Connector/ODBC
source is available. All ODBC 2.5 functions are supported, as are many others. See MySQL
Connector/ODBC Developer Guide.
• The Connector/J interface provides MySQL support for Java client programs that use JDBC
connections. Clients can be run on Windows or Unix. Connector/J source is available. See
MySQL Connector/J 5.1 Developer Guide.
• MySQL Connector/Net enables developers to easily create .NET applications that require
secure, high-performance data connectivity with MySQL. It implements the required ADO.NET
interfaces and integrates into ADO.NET aware tools. Developers can build applications using
their choice of .NET languages. MySQL Connector/Net is a fully managed ADO.NET driver
written in 100% pure C#. See MySQL Connector/Net Developer Guide.
Localization
• The server can provide error messages to clients in many languages. See Section 10.2,
“Setting the Error Message Language”.
• Full support for several different character sets, including latin1 (cp1252), german, big5,
ujis, several Unicode character sets, and more. For example, the Scandinavian characters “å”, “ä”
and “ö” are permitted in table and column names.
• All data is saved in the chosen character set.
• Sorting and comparisons are done according to the default character set and collation. is
possible to change this when the MySQL server is started (see Section 10.1.3.2, “Server
Character Set and Collation”). To see an example of very advanced sorting, look at the Czech
sorting code. MySQL Server supports many different character sets that can be specified at
compile time and runtime.
• The server time zone can be changed dynamically, and individual clients can specify their
own time zone. See Section 10.6, “MySQL Server Time Zone Support”.
Clients and Tools
• MySQL includes several client and utility programs. These include both command-line
programs such as mysqldump andmysqladmin, and graphical programs such as MySQL
Workbench.
• MySQL Server has built-in support for SQL statements to check, optimize, and repair
tables. These statements are available from the command line through the mysqlcheck client.
MySQL also includes myisamchk, a very fast command-line utility for performing these
operations on MyISAM tables. See Chapter 4, MySQL Programs.
• MySQL programs can be invoked with the --help or -? option to obtain online assistance.

History of MySQL
We started out with the intention of using the mSQL database system to connect to our tables
using our own fast low-level (ISAM) routines. However, after some testing, we came to the
conclusion that mSQL was not fast enough or flexible enough for our needs. This resulted in a
new SQL interface to our database but with almost the same API interface as mSQL. This API
was designed to enable third-party code that was written for use with mSQL to be ported easily
for use with MySQL.
MySQL is named after co-founder Monty Widenius's daughter, My.
The name of the MySQL Dolphin (our logo) is “Sakila,” which was chosen from a huge list of
names suggested by users in our “Name the Dolphin” contest. The winning name was submitted
by Ambrose Twebaze, an Open Source software developer from Swaziland, Africa. According to
Ambrose, the feminine name Sakila has its roots in SiSwati, the local language of Swaziland.
Sakila is also the name of a town in Arusha, Tanzania, near Ambrose's country of origin, Uganda

EXECUTION STEPS :
Installation of Mysql on Server
[root@localhost bvcoew]# yum install mysql-server
Loaded plugins: langpacks, refresh-packagekit
Resolving Dependencies
There are unfinished transactions remaining. You might consider running yum-complete-
transaction, or "yum history redo last", first to finish them. If that doesn't work you'll have to try
removing/installing packages by hand (maybe package-cleanup can help).
--> Running transaction check
---> Package mariadb-server.x86_64 1:5.5.39-1.fc19 will be installed
--> Processing Dependency: mariadb-libs(x86-64) = 1:5.5.39-1.fc19 for package: 1:mariadb-
server-5.5.39-1.fc19.x86_64
--> Processing Dependency: mariadb(x86-64) = 1:5.5.39-1.fc19 for package: 1:mariadb-server-
5.5.39-1.fc19.x86_64
--> Processing Dependency: perl-DBI for package: 1:mariadb-server-5.5.39-1.fc19.x86_64
--> Processing Dependency: perl-DBD-MySQL for package: 1:mariadb-server-5.5.39-
1.fc19.x86_64
--> Processing Dependency: perl(DBI) for package: 1:mariadb-server-5.5.39-1.fc19.x86_64
--> Processing Dependency: libjemalloc.so.1()(64bit) for package: 1:mariadb-server-5.5.39-
1.fc19.x86_64
--> Running transaction check
---> Package jemalloc.x86_64 0:3.6.0-1.fc19 will be installed
---> Package mariadb.x86_64 1:5.5.39-1.fc19 will be installed
---> Package mariadb-libs.x86_64 1:5.5.39-1.fc19 will be installed
---> Package perl-DBD-MySQL.x86_64 0:4.023-2.fc19 will be installed
---> Package perl-DBI.x86_64 0:1.623-2.fc19 will be installed
--> Processing Dependency: perl(RPC::PlServer) >= 0.2001 for package: perl-DBI-1.623-
2.fc19.x86_64
--> Processing Dependency: perl(RPC::PlClient) >= 0.2000 for package: perl-DBI-1.623-
2.fc19.x86_64
--> Processing Dependency: perl(Coro::Select) for package: perl-DBI-1.623-2.fc19.x86_64
--> Processing Dependency: perl(Coro::Handle) for package: perl-DBI-1.623-2.fc19.x86_64
--> Processing Dependency: perl(Coro) for package: perl-DBI-1.623-2.fc19.x86_64
--> Running transaction check
---> Package perl-Coro.x86_64 0:6.23-2.fc19 will be installed
--> Processing Dependency: perl(IO::AIO) >= 3.1 for package: perl-Coro-6.23-2.fc19.x86_64
--> Processing Dependency: perl(Guard) >= 0.5 for package: perl-Coro-6.23-2.fc19.x86_64
--> Processing Dependency: perl(Event) >= 1.08 for package: perl-Coro-6.23-2.fc19.x86_64
--> Processing Dependency: perl(EV) >= 4 for package: perl-Coro-6.23-2.fc19.x86_64
--> Processing Dependency: perl(AnyEvent::BDB) >= 1 for package: perl-Coro-6.23-
2.fc19.x86_64
--> Processing Dependency: perl(AnyEvent::AIO) >= 1 for package: perl-Coro-6.23-
2.fc19.x86_64
--> Processing Dependency: perl(AnyEvent) >= 7 for package: perl-Coro-6.23-2.fc19.x86_64
--> Processing Dependency: perl(common::sense) for package: perl-Coro-6.23-2.fc19.x86_64
--> Processing Dependency: perl(BDB) for package: perl-Coro-6.23-2.fc19.x86_64
--> Processing Dependency: perl(AnyEvent::Util) for package: perl-Coro-6.23-2.fc19.x86_64
--> Processing Dependency: perl(AnyEvent::Socket) for package: perl-Coro-6.23-2.fc19.x86_64
--> Processing Dependency: perl(AnyEvent::DNS) for package: perl-Coro-6.23-2.fc19.x86_64
---> Package perl-PlRPC.noarch 0:0.2020-13.fc19 will be installed
--> Processing Dependency: perl(Net::Daemon) >= 0.13 for package: perl-PlRPC-0.2020-
13.fc19.noarch
--> Processing Dependency: perl(Net::Daemon::Test) for package: perl-PlRPC-0.2020-
13.fc19.noarch
--> Processing Dependency: perl(Net::Daemon::Log) for package: perl-PlRPC-0.2020-
13.fc19.noarch
--> Running transaction check
---> Package perl-AnyEvent.x86_64 0:7.04-2.fc19 will be installed
--> Processing Dependency: perl(Task::Weaken) for package: perl-AnyEvent-7.04-
2.fc19.x86_64
---> Package perl-AnyEvent-AIO.noarch 0:1.1-11.fc19 will be installed
---> Package perl-AnyEvent-BDB.noarch 0:1.1-10.fc19 will be installed
---> Package perl-BDB.x86_64 0:1.90-4.fc19 will be installed
---> Package perl-EV.x86_64 0:4.11-2.fc19 will be installed
---> Package perl-Event.x86_64 0:1.21-2.fc19 will be installed
---> Package perl-Guard.x86_64 0:1.022-4.fc19 will be installed
---> Package perl-IO-AIO.x86_64 0:4.15-4.fc19 will be installed
---> Package perl-Net-Daemon.noarch 0:0.48-5.fc19 will be installed
---> Package perl-common-sense.noarch 0:3.6-4.fc19 will be installed
--> Running transaction check
---> Package perl-Task-Weaken.noarch 0:1.04-6.fc19 will be installed
--> Finished Dependency Resolution
Dependencies Resolved
=====================================================================
=====================================================================
============
Package Arch Version Repository
Size
=====================================================================
=====================================================================
============
Installing:
mariadb-server x86_64 1:5.5.39-1.fc19 updates
11 M
Installing for dependencies:
jemalloc x86_64 3.6.0-1.fc19 updates
105 k
mariadb x86_64 1:5.5.39-1.fc19 updates
8.8 M
mariadb-libs x86_64 1:5.5.39-1.fc19 updates
749 k
perl-AnyEvent x86_64 7.04-2.fc19 fedora
427 k
perl-AnyEvent-AIO noarch 1.1-11.fc19 fedora
8.9 k
perl-AnyEvent-BDB noarch 1.1-10.fc19 fedora
8.9 k
perl-BDB x86_64 1.90-4.fc19 fedora
73 k
perl-Coro x86_64 6.23-2.fc19 fedora
254 k
perl-DBD-MySQL x86_64 4.023-2.fc19 fedora
140 k
perl-DBI x86_64 1.623-2.fc19 fedora
806 k
perl-EV x86_64 4.11-2.fc19 fedora
256 k
perl-Event x86_64 1.21-2.fc19 fedora
282 k
perl-Guard x86_64 1.022-4.fc19 fedora
19 k
perl-IO-AIO x86_64 4.15-4.fc19 fedora
111 k
perl-Net-Daemon noarch 0.48-5.fc19 fedora
51 k
perl-PlRPC noarch 0.2020-13.fc19 fedora
35 k
perl-Task-Weaken noarch 1.04-6.fc19 fedora
18 k
perl-common-sense noarch 3.6-4.fc19 fedora
28 k

Transaction Summary
=====================================================================
=====================================================================
============
Install 1 Package (+18 Dependent packages)

Total size: 23 M
Total download size: 23 M
Installed size: 116 M
Is this ok [y/d/N]: y
Downloading packages:
perl-AnyEvent-7.04-2.fc19.x86_ FAILED
https://ftp-stud.hs-
esslingen.de/pub/Mirrors/archive.fedoraproject.org/fedora/linux/releases/19/Everything/x86_64/
os/Packages/p/perl-AnyEvent-7.04-2.fc19.x86_64.rpm: [Errno 14] curl#60 - "Peer's Certificate
issuer is not recognized."
Trying other mirror.
mariadb-5.5.39-1.fc19.x86_64.r FAILED ] 0.0
B/s | 0 B --:--:-- ETA
https://ftp-stud.hs-
esslingen.de/pub/Mirrors/archive.fedoraproject.org/fedora/linux/updates/19/x86_64/mariadb-
5.5.39-1.fc19.x86_64.rpm: [Errno 14] curl#60 - "Peer's Certificate issuer is not recognized."
Trying other mirror.
(1/18): perl-AnyEvent-BDB-1.1-10.fc19.noarch.rpm
| 8.9 kB 00:00:06
(2/18): perl-BDB-1.90-4.fc19.x86_64.rpm
| 73 kB 00:00:05
(3/18): perl-AnyEvent-AIO-1.1-11.fc19.noarch.rpm
| 8.9 kB 00:00:12
(4/18): perl-Coro-6.23-2.fc19.x86_64.rpm |
254 kB 00:00:06
(5/18): perl-DBD-MySQL-4.023-2.fc19.x86_64.rpm
| 140 kB 00:00:09
(6/18): perl-DBI-1.623-2.fc19.x86_64.rpm
| 806 kB 00:00:10
(7/18): perl-Guard-1.022-4.fc19.x86_64.rpm
| 19 kB 00:00:00
(8/18): perl-Event-1.21-2.fc19.x86_64.rpm |
282 kB 00:00:04
(9/18): perl-Net-Daemon-0.48-5.fc19.noarch.rpm
| 51 kB 00:00:01
(10/18): perl-IO-AIO-4.15-4.fc19.x86_64.rpm
| 111 kB 00:00:06
(11/18): perl-Task-Weaken-1.04-6.fc19.noarch.rpm
| 18 kB 00:00:00
(12/18): perl-common-sense-3.6-4.fc19.noarch.rpm
| 28 kB 00:00:00
(13/18): perl-EV-4.11-2.fc19.x86_64.rpm |
256 kB 00:00:12
(14/18): perl-PlRPC-0.2020-13.fc19.noarch.rpm
| 35 kB 00:00:02
(15/18): mariadb-libs-5.5.39-1.fc19.x86_64.rpm
| 749 kB 00:00:33
(16/18): perl-AnyEvent-7.04-2.fc19.x86_64.rpm
| 427 kB 00:00:03
(17/18): mariadb-server-5.5.39-1.fc19.x86_64.rpm
| 11 MB 00:02:54
(18/18): mariadb-5.5.39-1.fc19.x86_64.rpm
| 8.8 MB 00:02:51
---------------------------------------------------------------------------------------------------------------------
---------------------------------
Total 117 kB/s | 23 MB
03:22
Running transaction check
Running transaction test
Transaction test succeeded
Running transaction
Warning: RPMDB altered outside of yum.
** Found 49 pre-existing rpmdb problem(s), 'yum check' output follows:
audit-libs-2.3.7-1.fc19.x86_64 is a duplicate with audit-libs-2.3.1-2.fc19.x86_64
augeas-libs-1.2.0-1.fc19.x86_64 is a duplicate with augeas-libs-1.0.0-2.fc19.x86_64
bash-4.2.53-1.fc19.x86_64 is a duplicate with bash-4.2.45-1.fc19.x86_64
boost-system-1.53.0-14.fc19.x86_64 is a duplicate with boost-system-1.53.0-6.fc19.x86_64
boost-thread-1.53.0-14.fc19.x86_64 is a duplicate with boost-thread-1.53.0-6.fc19.x86_64
coreutils-8.21-13.fc19.x86_64 is a duplicate with coreutils-8.21-11.fc19.x86_64
cyrus-sasl-lib-2.1.26-10.fc19.x86_64 is a duplicate with cyrus-sasl-lib-2.1.26-8.fc19.x86_64
dbus-glib-0.100-5.fc19.x86_64 is a duplicate with dbus-glib-0.100-4.fc19.x86_64
1:dbus-libs-1.6.28-1.fc19.x86_64 is a duplicate with 1:dbus-libs-1.6.8-5.fc19.x86_64
elfutils-libelf-0.160-1.fc19.x86_64 is a duplicate with elfutils-libelf-0.155-5.fc19.x86_64
file-libs-5.11-13.fc19.x86_64 is a duplicate with file-libs-5.11-9.fc19.x86_64
freetype-2.4.11-7.fc19.x86_64 is a duplicate with freetype-2.4.11-6.fc19.x86_64
glib2-2.36.4-1.fc19.x86_64 is a duplicate with glib2-2.36.3-2.fc19.x86_64
grep-2.14-4.fc19.x86_64 is a duplicate with grep-2.14-3.fc19.x86_64
gstreamer1-1.0.10-1.fc19.x86_64 is a duplicate with gstreamer1-1.0.7-1.fc19.x86_64
json-glib-0.16.2-1.fc19.x86_64 is a duplicate with json-glib-0.16.0-1.fc19.x86_64
keyutils-libs-1.5.9-1.fc19.x86_64 is a duplicate with keyutils-libs-1.5.5-4.fc19.x86_64
krb5-libs-1.11.3-25.fc19.x86_64 is a duplicate with krb5-libs-1.11.3-1.fc19.x86_64
lcms2-2.6-1.fc19.x86_64 is a duplicate with lcms2-2.4-6.fc19.x86_64
libacl-2.2.51-10.fc19.x86_64 is a duplicate with libacl-2.2.51-9.fc19.x86_64
libblkid-2.23.2-5.fc19.x86_64 is a duplicate with libblkid-2.23.1-3.fc19.x86_64
libbluray-0.6.2-1.fc19.x86_64 is a duplicate with libbluray-0.2.3-2.fc19.x86_64
libcap-ng-0.7.4-1.fc19.x86_64 is a duplicate with libcap-ng-0.7.3-3.fc19.x86_64
libdhash-0.4.3-20.fc19.x86_64 is a duplicate with libdhash-0.4.3-17.fc19.x86_64
libgcc-4.8.3-7.fc19.x86_64 is a duplicate with libgcc-4.8.1-1.fc19.x86_64
libgcrypt-1.5.3-2.fc19.x86_64 is a duplicate with libgcrypt-1.5.2-1.fc19.x86_64
libgomp-4.8.3-7.fc19.x86_64 is a duplicate with libgomp-4.8.1-1.fc19.x86_64
libicu-50.1.2-9.fc19.x86_64 is a duplicate with libicu-50.1.2-5.fc19.x86_64
libjpeg-turbo-1.3.1-2.fc19.x86_64 is a duplicate with libjpeg-turbo-1.2.90-2.fc19.x86_64
libmount-2.23.2-5.fc19.x86_64 is a duplicate with libmount-2.23.1-3.fc19.x86_64
libnl3-3.2.22-3.fc19.x86_64 is a duplicate with libnl3-3.2.21-1.fc19.x86_64
2:libpng-1.5.13-3.fc19.x86_64 is a duplicate with 2:libpng-1.5.13-2.fc19.x86_64
libproxy-0.4.11-7.fc19.x86_64 is a duplicate with libproxy-0.4.11-3.fc19.x86_64
libpwquality-1.2.3-1.fc19.x86_64 is a duplicate with libpwquality-1.2.1-2.fc19.x86_64
libsoup-2.42.3.1-1.fc19.x86_64 is a duplicate with libsoup-2.42.2-1.fc19.x86_64
libstdc++-4.8.3-7.fc19.x86_64 is a duplicate with libstdc++-4.8.1-1.fc19.x86_64
libtevent-0.9.19-1.fc19.x86_64 is a duplicate with libtevent-0.9.18-1.fc19.x86_64
libuuid-2.23.2-5.fc19.x86_64 is a duplicate with libuuid-2.23.1-3.fc19.x86_64
libxml2-2.9.1-2.fc19.x86_64 is a duplicate with libxml2-2.9.1-1.fc19.x86_64
nspr-4.10.7-1.fc19.x86_64 is a duplicate with nspr-4.9.6-1.fc19.x86_64
nss-util-3.17.2-1.fc19.x86_64 is a duplicate with nss-util-3.14.3-1.fc19.x86_64
pam-1.1.6-12.fc19.x86_64 is a duplicate with pam-1.1.6-11.fc19.1.x86_64
pcre-8.32-12.fc19.x86_64 is a duplicate with pcre-8.32-7.fc19.x86_64
popt-1.16-2.fc19.x86_64 is a duplicate with popt-1.13-14.fc19.x86_64
readline-6.2-8.fc19.x86_64 is a duplicate with readline-6.2-6.fc19.x86_64
shared-mime-info-1.1-6.fc19.x86_64 is a duplicate with shared-mime-info-1.1-4.fc19.x86_64
sqlite-3.8.3-1.fc19.x86_64 is a duplicate with sqlite-3.7.17-1.fc19.x86_64
systemd-libs-204-21.fc19.x86_64 is a duplicate with systemd-libs-204-8.fc19.x86_64
tcp_wrappers-libs-7.6-75.fc19.x86_64 is a duplicate with tcp_wrappers-libs-7.6-73.fc19.x86_64
Installing : perl-common-sense-3.6-4.fc19.noarch
1/19
Installing : 1:mariadb-libs-5.5.39-1.fc19.x86_64
2/19
Installing : perl-IO-AIO-4.15-4.fc19.x86_64
3/19
Installing : perl-BDB-1.90-4.fc19.x86_64
4/19
Installing : jemalloc-3.6.0-1.fc19.x86_64
5/19
Installing : 1:mariadb-5.5.39-1.fc19.x86_64
6/19
Installing : perl-EV-4.11-2.fc19.x86_64
7/19
Installing : perl-Task-Weaken-1.04-6.fc19.noarch
8/19
Installing : perl-AnyEvent-7.04-2.fc19.x86_64
9/19
Installing : perl-AnyEvent-AIO-1.1-11.fc19.noarch
10/19
Installing : perl-AnyEvent-BDB-1.1-10.fc19.noarch
11/19
Installing : perl-Event-1.21-2.fc19.x86_64
12/19
Installing : perl-Guard-1.022-4.fc19.x86_64
13/19
Installing : perl-Coro-6.23-2.fc19.x86_64
14/19
Installing : perl-Net-Daemon-0.48-5.fc19.noarch
15/19
Installing : perl-PlRPC-0.2020-13.fc19.noarch
16/19
Installing : perl-DBI-1.623-2.fc19.x86_64
17/19
Installing : perl-DBD-MySQL-4.023-2.fc19.x86_64
18/19
Installing : 1:mariadb-server-5.5.39-1.fc19.x86_64
19/19
Verifying : 1:mariadb-server-5.5.39-1.fc19.x86_64
1/19
Verifying : perl-AnyEvent-AIO-1.1-11.fc19.noarch
2/19
Verifying : perl-EV-4.11-2.fc19.x86_64
3/19
Verifying : 1:mariadb-5.5.39-1.fc19.x86_64
4/19
Verifying : perl-Coro-6.23-2.fc19.x86_64
5/19
Verifying : jemalloc-3.6.0-1.fc19.x86_64
6/19
Verifying : perl-Net-Daemon-0.48-5.fc19.noarch
7/19
Verifying : perl-AnyEvent-BDB-1.1-10.fc19.noarch
8/19
Verifying : 1:mariadb-libs-5.5.39-1.fc19.x86_64
9/19
Verifying : perl-AnyEvent-7.04-2.fc19.x86_64
10/19
Verifying : perl-DBI-1.623-2.fc19.x86_64
11/19
Verifying : perl-common-sense-3.6-4.fc19.noarch
12/19
Verifying : perl-Guard-1.022-4.fc19.x86_64
13/19
Verifying : perl-PlRPC-0.2020-13.fc19.noarch
14/19
Verifying : perl-IO-AIO-4.15-4.fc19.x86_64
15/19
Verifying : perl-Event-1.21-2.fc19.x86_64
16/19
Verifying : perl-Task-Weaken-1.04-6.fc19.noarch
17/19
Verifying : perl-DBD-MySQL-4.023-2.fc19.x86_64
18/19
Verifying : perl-BDB-1.90-4.fc19.x86_64
19/19
Installed:
mariadb-server.x86_64 1:5.5.39-1.fc19

Dependency Installed:
jemalloc.x86_64 0:3.6.0-1.fc19 mariadb.x86_64 1:5.5.39-1.fc19
mariadb-libs.x86_64 1:5.5.39-1.fc19
perl-AnyEvent.x86_64 0:7.04-2.fc19 perl-AnyEvent-AIO.noarch 0:1.1-11.fc19
perl-AnyEvent-BDB.noarch 0:1.1-10.fc19
perl-BDB.x86_64 0:1.90-4.fc19 perl-Coro.x86_64 0:6.23-2.fc19 perl-
DBD-MySQL.x86_64 0:4.023-2.fc19
perl-DBI.x86_64 0:1.623-2.fc19 perl-EV.x86_64 0:4.11-2.fc19 perl-
Event.x86_64 0:1.21-2.fc19
perl-Guard.x86_64 0:1.022-4.fc19 perl-IO-AIO.x86_64 0:4.15-4.fc19 perl-
Net-Daemon.noarch 0:0.48-5.fc19
perl-PlRPC.noarch 0:0.2020-13.fc19 perl-Task-Weaken.noarch 0:1.04-6.fc19
perl-common-sense.noarch 0:3.6-4.fc19

Complete!

II] On SERVER
[bvcoew@localhost ~]$ su
Password:
[root@localhost bvcoew]# service mysqld start
Redirecting to /bin/systemctl start mysqld.service
[root@localhost bvcoew]# mysql
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 2
Server version: 5.5.37 MySQL Community Server (GPL)
Copyright (c) 2000, 2014, Oracle and/or its affiliates. All rights reserved.
Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql> Bye

[root@localhost bvcoew]# /usr/bin/mysql_secure_installation

NOTE: RUNNING ALL PARTS OF THIS SCRIPT IS RECOMMENDED FOR ALL MySQL
SERVERS IN PRODUCTION USE! PLEASE READ EACH STEP CAREFULLY!

In order to log into MySQL to secure it, we'll need the current
password for the root user. If you've just installed MySQL, and
you haven't set the root password yet, the password will be blank,
so you should just press enter here.

Enter current password for root (enter for none):


ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: YES)
Enter current password for root (enter for none):
OK, successfully used password, moving on...

Setting the root password ensures that nobody can log into the MySQL
root user without the proper authorisation.

Set root password? [Y/n] y


New password:
Re-enter new password:
Password updated successfully!
Reloading privilege tables..
... Success!

By default, a MySQL installation has an anonymous user, allowing anyone


to log into MySQL without having to have a user account created for
them. This is intended only for testing, and to make the installation
go a bit smoother. You should remove them before moving into a
production environment.

Remove anonymous users? [Y/n] y


... Success!

Normally, root should only be allowed to connect from 'localhost'. This


ensures that someone cannot guess at the root password from the network.

Disallow root login remotely? [Y/n] y


... Success!

By default, MySQL comes with a database named 'test' that anyone can
access. This is also intended only for testing, and should be removed
before moving into a production environment.

Remove test database and access to it? [Y/n] y


- Dropping test database...
... Success!
- Removing privileges on test database...
... Success!

Reloading the privilege tables will ensure that all changes made so far
will take effect immediately.

Reload privilege tables now? [Y/n] y


... Success!

Cleaning up...

All done! If you've completed all of the above steps, your MySQL
installation should now be secure.

Thanks for using MySQL!

[root@localhost bvcoew]# mysql -u root -p


Enter password:
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 14
Server version: 5.5.37 MySQL Community Server (GPL)
Copyright (c) 2000, 2014, Oracle and/or its affiliates. All rights reserved.
Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

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

mysql> create database maindb;


Query OK, 1 row affected (0.00 sec)

mysql> create user 'groupone'@'%' identified by 'student';


Query OK, 0 rows affected (0.00 sec)

mysql> grant all on *.* to 'groupone'@'%';


Query OK, 0 rows affected (0.00 sec)

mysql> use maindb;


Database changed
mysql> create table student(name varchar(10),marks int,city varchar(10));
Query OK, 0 rows affected (0.12 sec)

mysql> insert into student values('abc',67,'pune');


Query OK, 1 row affected (0.03 sec)

mysql> insert into student values('fdg',78,'katraj');


Query OK, 1 row affected (0.03 sec)

mysql> insert into student values('fd',89,'katraj');


Query OK, 1 row affected (0.04 sec)

mysql> desc student;


+-------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------+-------------+------+-----+---------+-------+
| name | varchar(10) | YES | | NULL | |
| marks | int(11) | YES | | NULL | |
| city | varchar(10) | YES | | NULL | |
+-------+-------------+------+-----+---------+-------+
3 rows in set (0.00 sec)

mysql> select * from student;


+------+-------+--------+
| name | marks | city |
+------+-------+--------+
| abc | 67 | pune |
| fdg | 78 | katraj |
| fd | 89 | katraj |
+------+-------+--------+
3 rows in set (0.00 sec)

mysql> Bye
[root@localhost bvcoew]# service mysqld restart
Redirecting to /bin/systemctl restart mysqld.service

[root@localhost bvcoew]# systemctl disable firewalld

rm '/etc/systemd/system/dbus-org.fedoraproject.FirewallD1.service'
rm '/etc/systemd/system/basic.target.wants/firewalld.service'

[root@localhost bvcoew]# systemctl stop firewalld

[root@localhost bvcoew]#

ON CLIENT
[root@localhost bvcoew]# locate my.cnf
/etc/my.cnf
/etc/my.cnf.d
/etc/my.cnf.d/mysql-clients.cnf
[root@localhost bvcoew]#gedit /etc/my.cnf
// add a line below[mysqld] :-
//bind-address=server IP-address 172.24.3.23

[root@localhost bvcoew]# systemctl stop mysqld.service


[root@localhost bvcoew]# systemctl start mysqld.service
Job for mysqld.service failed. See 'systemctl status mysqld.service' and 'journalctl -xn' for details.
[root@localhost bvcoew]# mysql -h 172.24.3.35 -u groupone -p
Enter password:
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 3
Server version: 5.5.37 MySQL Community Server (GPL)
Copyright (c) 2000, 2014, Oracle and/or its affiliates. All rights reserved.
Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql> use maindb


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
mysql> select * from student;
+------+-------+--------+
| name | marks | city |
+------+-------+--------+
| abc | 67 | pune |
| fdg | 78 | katraj |
| fd | 89 | katraj |
+------+-------+--------+
3 rows in set (0.00 sec)

mysql>

CONCLUSION : students have studied open source database management system and installed
Mysql database
GROUP A

EXPERIMENT 2

OBJECTIVE : Study Design and implementation of SQL DDL statements which demonstrate
the use of SQL objects such as Table, View, Index, Sequence, Synonym

PROBLEM STATEMENT: Design and Develop SQL DDL statements which demonstrate the
use of SQL objects such as Table, View, Index, Sequence, Synonym

HARDWARE REQUIREMENT :

2 GHz dual core processor.


2 GiB RAM (system memory)
25 GB of hard-drive space (or USB stick, memory card or external drive but see LiveCD for an
alternative approach)

SOFTWARE REQUIREMENT :
Operating System- Ubuntu 16.04
Database- Mysql

OUTCOME : Student are able to Design and Implement of SQL DDL statements for SQL
objects such as Table, View, Index, Sequence, Synonym

THEORY :
managing data held in a relational database management system (RDBMS).

Originally based upon relational algebra and tuple relational calculus, SQL consists of a data
definition language and a data manipulation language. The scope of SQL includes data insert,
query, update and delete, schema creation and modification, and data access control.

MySQL :-

MySQL officially, but also called is the world's second most widely used open-source relational
database management system . It is named after co-founder Michael Widenius's daughter, My.
The SQL phrase stands for Structured Query Language.

The MySQL development project has made its source code available under the terms of the
GNU General Public License, as well as under a variety of proprietary agreements. MySQL was
owned and sponsored by a single for-profit firm, the Swedish company MySQL AB, now owned
by Oracle Corporation.

Features :-
- High performance

- High availability

- Scalability & Flexibility

- Robust transactional support

- Storage data protection

- Managment ease

What is an Operator in SQL?

An operator is a reserved word or a character used primarily in an SQL statement's WHERE


clause to perform operation(s), such as comparisons and arithmetic operations.

Operators are used to specify conditions in an SQL statement and to serve as conjunctions for
multiple conditions in a statement.

- Arithmetic operators

- Comparison operators

- Logical operators

- Operators used to negate conditions

DDL - Data Definition Language:

CREATE statement -

The create table command defines each column of the table yniquely. Each column has at least
three attributes : column name, datatypes, size

Syntax -

CREATE TABLE <TABLE NAME> <COLUMN NAME><DATATYPE><SIZE>

Desceribing tables _

DESC statement is used to view the srtucture of the created tables.

Syntax -

desc<name of table>
ALTER statement :-

If you are adding constraints to the existing table then you have to use ALTER satement as you
are altering or changing the structure of the already existing table.

INSERT statement :-

To insert data into MySQL table, you would need to use SQL INSERT INTO command. You
can insert data into MySQL table by using mysql> prompt

Syntax -

INSERT INTO table_name ( field1, field2,...fieldN ) VALUES ( value1, value2,...valueN );

The standard SQL commands to interact with relational databases are CREATE, SELECT,
INSERT, UPDATE, DELETE and DROP. These commands can be classified into groups based
on their nature:

DROP Deletes an entire table, a view of a table or other object in the database.

DML - Data Manipulation Language:

INSERT Creates a record

UPDATE Modifies records

DELETE Deletes records

DCL -Data Control Language:

GRANT Gives a privilege to user

REVOKE Takes back privileges granted from user

DQL - Data Query Language:

SELECT SELECT Retrieves certain records from one or more tables


SQL

SQL Structured Query Language is a special-purpose programming language designed for


EXECUTION STEPS :

[bvcoew@localhost ~]$ su

Password:

[root@localhost bvcoew]# service mysqld start

Redirecting to /bin/systemctl start mysqld.service

[root@localhost bvcoew]# mysql

Welcome to the MariaDB monitor. Commands end with ; or \g.

Your MariaDB connection id is 2

Server version: 5.5.39-MariaDB MariaDB Server

Copyright (c) 2000, 2014, Oracle, Monty Program Ab and others.

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

MariaDB [(none)]> use pearl;

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 [pearl]> select * from supplier;

+----------+------------+--------+---------+

| suppl_no | suppl_name | status | city |

+----------+------------+--------+---------+

| 1 | s1 | 15 | pune |

| 2 | s2 | 25 | chennai |
| 3 | s3 | 33 | mumbai |

+----------+------------+--------+---------+

3 rows in set (0.07 sec)

MariaDB [pearl]> select * from part;

+---------+-----------+--------+--------+---------+

| part_no | part_name | color | weight | city |

+---------+-----------+--------+--------+---------+

| 101 | p1 | red | 65 | pune |

| 201 | p2 | yellow | 50 | chennai |

| 301 | p3 | orange | 40 | mumbai |

+---------+-----------+--------+--------+---------+

3 rows in set (0.00 sec)

MariaDB [pearl]> select * from shipment;

+----------+---------+----------+

| suppl_no | part_no | quantity |

+----------+---------+----------+

| 1| 101 | 100 |

| 2| 201 | 500 |

| 3| 301 | 900 |

+----------+---------+----------+

3 rows in set (0.00 sec)


Create index on table supplier by using supp_number.
MariaDB [pearl]> create index supp_index on supplier(supp_no);

Query OK, 0 rows affected (0.10 sec)

Records: 0 Duplicates: 0 Warnings: 0

Create index on table supplier by using supp_name.


MariaDB[pearl]> create index s_index on supplier(supp_name);

Query OK, 0 rows affected (0.09 sec)

Records: 0 Duplicates: 0 Warnings: 0

Show all the indexes on supplier.


MariaDB [pearl]> show index from supplier from thesuppliers;

+----------+------------+------------+--------------+-------------+-----------+-------------+----------+------
--+------+------------+---------+---------------+

| Table | Non_unique | Key_name | Seq_in_index | Column_name | Collation | Cardinality |


Sub_part | Packed | Null | Index_type | Comment | Index_comment |

+----------+------------+------------+--------------+-------------+-----------+-------------+----------+------
--+------+------------+---------+---------------+

| supplier | 0 | PRIMARY | 1 | supp_no |A | 5| NULL | NULL |


| BTREE | | |

| supplier | 1 | supp_index | 1 | supp_no |A | 5| NULL | NULL | |


BTREE | | |

| supplier | 1 | s_index | 1 | supp_name | A | 5| NULL | NULL |


YES | BTREE | | |

+----------+------------+------------+--------------+-------------+-----------+-------------+----------+------
--+------+------------+---------+---------------+

3 rows in set (0.00 sec)

Drop the index supplier name on table supplier.


MariaDB [pearl]> alter table supplier drop index s_index;

Query OK, 0 rows affected (0.07 sec)

Records: 0 Duplicates: 0 Warnings: 0

MariaDB [pearl]> show index from supplier from thesuppliers;

+----------+------------+------------+--------------+-------------+-----------+-------------+----------+------
--+------+------------+---------+---------------+

| Table | Non_unique | Key_name | Seq_in_index | Column_name | Collation | Cardinality |


Sub_part | Packed | Null | Index_type | Comment | Index_comment |

+----------+------------+------------+--------------+-------------+-----------+-------------+----------+------
--+------+------------+---------+---------------+

| supplier | 0 | PRIMARY | 1 | supp_no |A | 5| NULL | NULL |


| BTREE | | |

| supplier | 1 | supp_index | 1 | supp_no |A | 5| NULL | NULL | |


BTREE | | |

+----------+------------+------------+--------------+-------------+-----------+-------------+----------+------
--+------+------------+---------+---------------+

2 rows in set (0.00 sec)

Create a view form supplier having city chennai and status grater than 25

mysql> create view viewsup as select * from supplier where city='chennai' and status >25;

Query OK, 0 rows affected (0.30 sec)

mysql> select *from viewsup;

+--------+----------+--------+---------+

| sup_no | sup_name | status | city |

+--------+----------+--------+---------+
| p1 | Ajay | 200 | chennai |

| S1 | Ajay | 200 | chennai |

+--------+----------+--------+---------+

2 rows in set (0.00 sec)

Update new record in view for chennai supplier.

mysql> update viewsup set sup_name='shreya' where city='chennai';

Query OK, 2 rows affected (0.05 sec)

Rows matched: 2 Changed: 2 Warnings: 0

mysql> select * from viewsup;

+--------+----------+--------+---------+

| sup_no | sup_name | status | city |

+--------+----------+--------+---------+

| p1 | shreya | 200 | chennai |

| S1 | shreya | 200 | chennai |

+--------+----------+--------+---------+

2 rows in set (0.00 sec

Drop a view suppl_pune.

mysql> drop view vw;

Query OK, 0 rows affected (0.00 sec)

Create a view form supplier having city chennai and status grater than 25
mysql> create view viewsup as select * from supplier where city='chennai' and status >25;

Query OK, 0 rows affected (0.30 sec)

mysql> select *from viewsup;

+--------+----------+--------+---------+

| sup_no | sup_name | status | city |

+--------+----------+--------+---------+

| p1 | Ajay | 200 | chennai |

| S1 | Ajay | 200 | chennai |

+--------+----------+--------+---------+

2 rows in set (0.00 sec)

Update new record in view for chennai supplier.


mysql> update viewsup set sup_name='shreya' where city='chennai';

Query OK, 2 rows affected (0.05 sec)

Rows matched: 2 Changed: 2 Warnings: 0

mysql> select * from viewsup;

+--------+----------+--------+---------+

| sup_no | sup_name | status | city |

+--------+----------+--------+---------+

| p1 | shreya | 200 | chennai |

| S1 | shreya | 200 | chennai |

+--------+----------+--------+---------+

2 rows in set (0.00 sec)

33. Drop a view suppl_pune.


mysql> drop view vw;

Query OK, 0 rows affected (0.00 sec)

CONCLUSION : Student successfully Designed and Implemented of SQL DDL statements for
SQL objects such as Table, View, Index, Sequence, Synonym
GROUP A

EXPERIMENT 3

OBJECTIVE :To Study Design and implementation of at least 10 SQL queries for suitable
database application using SQL DML statements: Insert, Select, Update, Delete with operators,
functions, and set operator.

PROBLEM STATEMENT: Design at least 10 SQL queries for suitable database application
using SQL DML statements: Insert, Select, Update, Delete with operators, functions, and set
operator.

HARDWARE REQUIREMENT :

2 GHz dual core processor.


2 GiB RAM (system memory)
25 GB of hard-drive space (or USB stick, memory card or external drive but see LiveCD for an
alternative approach)

SOFTWARE REQUIREMENT :
Operating System- Ubuntu 16.04
Database- Mysql

OUTCOME : After completion of assignment student are able to implement SQL queries for
Inserting, Selecting, Updating, Deleting with operators, functions, and set operator.

EXECUTION STEPS :

GET SUPPLIER NO. AND STATUS FOR SUPPLIERS IN CHENNAI WITH STATUS>20.

MariaDB [pearl]> select suppl_no,status from supplier where city='chennai' and status>20;

+----------+--------+

| suppl_no | status |

+----------+--------+

| 2| 25 |

+----------+--------+
1 row in set (0.00 sec)

Get all the pair of supplier numbers such that the suppliers concerned are
colocated(i.e located in the same city).

MariaDB [pearl]> select a.supp_no as sa, b.supp_no as sb from supplier as a, supplier as b where
a.city=b.city and a.supp_no<b.supp_no;

+----+----+

| sa | sb |

+----+----+

|1 |3 |

+----+----+

GET FULL SUPPLIER INFORMATION FOR SUPPLIER WHO SUPPLIES PART P2.

MariaDB [pearl]> select supp_no,supp_name,supplier.city from supplier,part where part_no=12


and supplier.city=part.city and supp_no in (select supp_no from shipment where part_no=12);

+---------+-----------+--------+

| supp_no | supp_name | city |

+---------+-----------+--------+

|2 | Aditi | Kolhar |

+---------+-----------+--------+

1 row in set (0.00 sec)

GET SUPPLIER NAME FOR SUPPLIER WHO SUPPLIES AT LEAST ONE RED
PART.

MariaDB [pearl]> select suppl_name from supplier,part where supplier.city=part.city and


color='red';

+------------+

| suppl_name |

+------------+

| s1 |
+------------+

1 row in set (0.00 sec)

GET SUPPLIER NAME FOR SUPPLIER WHO SUPPLY AT LEAST ONE PART
SUPPLIED BY SUPPLIER S2.

MariaDB [pearl]> select distinct supp_no from shipment where part_no in(select part_no from
shipment where supp_no=2);

+---------+

| supp_no |

+---------+

|2 |

+---------+

1 row in set (0.00 sec)

DELETE SUPPLIER'S NAME FOR SUPPLIER WHO DO NOT SUPPLY PART P2.

MariaDB [pearl]> delete supp_name from supplier,shipment where part_no=14 and


supplier.supp_no=shipment.supp_no;

+-----------+

| supp_name |

+-----------+

| Hetanshi |

+-----------+

UPDATE COLOR TO RED AND CITY FOR 'NON-CHENNAI' PARTS WITH


WEIGHT>10 POUNDS.

MariaDB [pearl]> Update part set color=’RED’ where city!='chennai' and weight>=10;

+--------+--------+

| color | city |

+--------+--------+
| red | pune |

| orange | mumbai |

+--------+--------+

2 rows in set (0.03 sec)

FOR ALL PARTS GET PART NO AND WEIGHT OF PART IN GRAM.

MariaDB [pearl]> select part.part_no,part.weight*454 as gmwt from part;

+---------+-------+

| part_no | gmwt |

+---------+-------+

| 101 | 29510 |

| 201 | 22700 |

| 301 | 18160 |

+---------+-------+

3 rows in set (0.03 sec)

GET TOTAL NO. OF SUPPLIERS.

MariaDB [pearl]> select count(*) as n from supplier;

+---+

|n|

+---+

|3|

+---+

1 row in set (0.03 sec)


GET MINIMUM AND MAXIMUM QUANTITY FOR PART P2.

MariaDB [pearl]> select min(quantity) from shipment where part_no=101;

+---------------+

| min(quantity) |

+---------------+

| 100 |

+---------------+

1 row in set (0.01 sec)

MariaDB [pearl]> select max(quantity) from shipment where part_no=101;

+---------------+

| max(quantity) |

+---------------+

| 100 |

+---------------+

1 row in set (0.00 sec)

GET PART NO. FOR PARTS SUPPLIED BY MORE THAN SUPPLIER.

MariaDB [pearl]> select shipment.part_no from shipment group by shipment.part_no having


count(shipment.supp_no)>1;

+---------+

| part_no |

+---------+

| 12 |

| 15 |

+---------+
GET SUPPLIER NO. FROM SUPPLIER WITH STATUS GREATER THAN CURRENT
MAXIMUM STATUS IN THE SUPPLIER TABLE.

MariaDB [pearl]> select supp_no from supplier where status<(select max(status)from supplier);

+---------+

| supp_no |

+---------+

|1 |

|2 |

|3 |

|4 |

+---------+

GET ALL COMBINATIONS OF SUPPLIER AND PARTS INFORMATION SUCH


THAT SUPPLIER AND PARTS IN THE QUESTION ARE COLLOCATED

MariaDB [pearl]> select supplier.*,part_no,part_name from supplier,part where


supplier.city=part.city;

+----------+------------+--------+---------+---------+-----------+

| suppl_no | suppl_name | status | city | part_no | part_name |

+----------+------------+--------+---------+---------+-----------+

| 1 | s1 | 15 | pune | 101 | p1 |

| 2 | s2 | 25 | chennai | 201 | p2 |

| 3 | s3 | 33 | mumbai | 301 | p3 |

+----------+------------+--------+---------+---------+-----------+

3 rows in set (0.02 sec)

GET ALL PAIRS OF CITY NAMES SUCH THAT A SUPPLIER LOCATED IN FIRST
CITY SUPPLIES A PART STORED IN SECOND CITY.
MariaDB [pearl]> select distinct supplier.city as 'pune',part.city as chennai from supplier natural
join shipment natural join part;

+---------+---------+

| pune | chennai |

+---------+---------+

| pune | pune |

| chennai | chennai |

| mumbai | mumbai |

+---------+---------+

3 rows in set (0.05 sec)

FOR EACH PART SUPPLIED GET PART NO. AND TOTAL SHIPMENT QUANTITY

MariaDB [pearl]> select sum(shipment.quantity)from shipment group by part_no;

+------------------------+

| sum(shipment.quantity) |

+------------------------+

| 100 |

| 500 |

| 900 |

+------------------------+

3 rows in set (0.34 sec)

Delete all the records from project.

MariaDB [pearl]> delete from project;


Find average quantity supplied by the supplier.

MariaDB [pearl]>select avg(quantity) from supplier group by suppl_no;

+------------------------+

| avg(quantity) |

+------------------------+

| 100 |

| 500 |

| 900 |

+------------------------+

3 rows in set (0.34 sec)

Drop the table project.

MariaDB [pearl]>drop table project;

Query OK, 3 rows affected (0.05 sec)

CONCLUSION : Students successfully implemented SQL queries for suitable database


application using SQL DML statements: Insert, Select, Update, Delete with operators, functions,
and set operator.
GROUP A

EXPERIMENT 4

OBJECTIVE : To study Design and implementation of 10 SQL queries for suitable database
application using SQL DML statements: all types of Join, Sub-Query and View.

PROBLEM STATEMENT: Design at least 10 SQL queries for suitable database application
using SQL DML statements: all types of Join, Sub-Query and View.

HARDWARE REQUIREMENT :

2 GHz dual core processor.


2 GiB RAM (system memory)
25 GB of hard-drive space (or USB stick, memory card or external drive but see LiveCD for an
alternative approach)

SOFTWARE REQUIREMENT :
Operating System- Ubuntu 16.04
Database- Mysql

OUTCOME : After completion of assignment student are able to implement 10 SQL queries for
suitable database application using SQL DML statements: all types of Join, Sub-Query and
View.

EXECUTION STEPS :
Perform inner join on supplier and parts on 'city'.

mysql> select sup_name from supplier inner join parts on supplier.city=parts.city;

+----------+

| sup_name |

+----------+

| trupti |

| sneha |

| shreya |

+----------+
3 rows in set (0.00 sec)

Perform right outer join on shipment and project.


MariaDB [pearl]> select * from project right outer join shipment on city;

+---------+-----------+------+---------+---------+----------+

| proj_no | proj_name | city | supp_no | part_no | quantity |

+---------+-----------+------+---------+---------+----------+

| NULL | NULL | NULL | 1 | 11 | 5|

| NULL | NULL | NULL | 2 | 12 | 6|

| NULL | NULL | NULL | 4 | 14 | 15 |

| NULL | NULL | NULL | 2 | 15 | 34 |

+---------+-----------+------+---------+---------+----------+

4 rows in set, 32 warnings (0.00 sec)

Perform Left Outer join on Shipment and project.

mysql> select * from shipment left outer join project on shipment.part_no=project.part_no;

+--------+---------+--------+---------+-------+

| sup_no | part_no | weight | part_no | name |

+--------+---------+--------+---------+-------+

|1 | p1 | 20 | p1 | Sneha |

|2 | p2 | 10 | p2 | Mansi |
|3 | p3 | 270 | NULL | NULL |

|4 | p4 | 27 | NULL | NULL |

+--------+---------+--------+---------+-------+

4 rows in set (0.00 sec)

Perform inner join on supplier and parts on 'city'.

mysql> select sup_name from supplier inner join parts on supplier.city=parts.city;

+----------+

| sup_name |

+----------+

| trupti |

| sneha |

| shreya |

+----------+

3 rows in set (0.00 sec)

Perform Left Outer join on Shipment and project.

mysql> select * from shipment left outer join project on shipment.part_no=project.part_no;

+--------+---------+--------+---------+-------+

| sup_no | part_no | weight | part_no | name |

+--------+---------+--------+---------+-------+

|1 | p1 | 20 | p1 | Sneha |

|2 | p2 | 10 | p2 | Mansi |
|3 | p3 | 270 | NULL | NULL |

|4 | p4 | 27 | NULL | NULL |

+--------+---------+--------+---------+-------+

4 rows in set (0.00 sec)

CONCLUSION : Student successfully implemented SQL queries for suitable database


application using SQL DML statements: all types of Join, Sub-Query and View.
GROUP A

EXPERIMENT 5

OBJECTIVE : To study Unnamed PL/SQL code block and use of Control structure and
Exception handling is mandatory. Write a PL/SQL block of code for Library fine calculation.

PROBLEM STATEMENT: 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 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.

HARDWARE REQUIREMENT :

2 GHz dual core processor.


2 GB RAM (system memory)
25 GB of hard-drive space (or USB stick, memory card or external drive but see LiveCD for an
alternative approach)

SOFTWARE REQUIREMENT :
Operating System- Ubuntu 16.04
Database- Mysql

OUTCOME : After completion of assignment student are able to explain Unnamed PL/SQL
code block , use of Control structure and Exception handling is mandatory and write a PL/SQL
block of code for Library fine calculation.

THEORY :
Limitations of SQL
SQL is the most powerful and comprehensive database language. It is flexible and efficient. SQL is
designed for working with relational data. Even though it is powerful and efficient it has certain
limitations.
Some of the limitations are :
• SQL is a non-procedural language.
• SQL does not allow declaring and using the constants, variables.
• We cannot control the flow of execution using SQL.
• SQL processes a set of rows at a time and does not support row by row processing.
PL/SQL is the procedural language extension to the SQL, in which you can declare and use the
variables, constants, do exception handling and you can also write the program modules in the form
of PL/SQL subprograms. PL/SQL combines the features of a procedural Language with Structured
Query Language.

PL/SQL - Advantages and Features


The advantages and features of PL/SQL are as follows

Advantages of PL/SQL
Some of the advantages of PL/SQL are as follows

Support for SQL


PL/SQL is the procedural language extension to SQL and with this PL/SQL supports all the
functionalities of SQL.
This means PL/SQL is
SQL + Procedural Language Component.
SQL is an efficient database language and so we get all these features in PL/SQL also.

Improved performance
In SQL, every statement individually goes to the ORACLE server, get processed there and
we get the response. In PL/SQL, an entire block of statements can be sent to ORACLE
server at one time, where as SQL statements are processed one at a time. Thus, PL/SQL
block statements drastically reduce communication between the application and ORACLE.
This helps in improving the performance.

SQL PROCESSING
Oracle Client Oracle Server

SQL Statement

SQL Statement
SQL
Higher productivity
Users use procedural features to build applications. PL/SQL code is written in the form of
PL/SQL block. PL/SQL blocks can also be used in other ORACLE tools like ORACLE Forms,
ORACLE Reports. This code reusability increases the programmers productivity.

Portability
Applications written in PL/SQL are portable. We can port them from one environment to any
computer hardware and operating system environment running ORACLE. Programs need
not be tailored for the new environment.

Integration with ORACLE


Both PL/SQL and ORACLE are SQL based. PL/SQL variables have datatypes native to the
ORACLE RDBMS data dictionary. This gives you tight integration with ORACLE.

Features of PL/SQL
Some of the features of PL/SQL are as follows.
 We can define and use variables and constants in PL/SQL.
 PL/SQL provides control structures to control the flow of a program. The control structures
supported by PL/SQL are IF..THEN, LOOP, FOR..LOOP and Others.
 We can do row by row processing of data in PL/SQL. PL/SQL supports row by row
processing using the mechanism called CURSOR (explained later).
 We can handle pre-defined and user-defined error situations. Errors or warnings are called as
exceptions in PL/SQL. To handle these errors, you can write the code in the form of
Exception handlers in PL/SQL.
 We can write modular application by using sub programs. The different types of sub-
programs are procedures, functions and packages.
The Structure of a PL/SQL Program
The basic unit of code in any PL/SQL program is a block. All PL/SQL programs are composed of
blocks. These blocks can be written sequentially (one after the other) or nested (one inside the other).
Typically, each block is written to perform a logical unit of work in a program.

The Structure of PL/SQL Block


A PL/SQL block has the following structure.

DECLARE
Declarative section –
 PL/SQL variables, types, cursors, and local subprograms are defined here.
 This section is optional.
BEGIN
Executable section –
 Procedural and SQL statements are written here. This is the main section of the block.
 This section is required.
EXCEPTION
Exception handling section –
 Error handling code is written here.
 This section is optional.

END;

CONCLUSION : Student successfully implemented Unnamed PL/SQL code block , use of


Control structure and Exception handling is mandatory and write a PL/SQL block of code for
Library fine calculation.
GROUP A

EXPERIMENT 6

OBJECTIVE : To study and implement database cursors for given problem statement.

PROBLEM 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 table already exist in the second table then that data should be skipped.

HARDWARE REQUIREMENT :

2 GHz dual core processor.


2 GiB RAM (system memory)
25 GB of hard-drive space (or USB stick, memory card or external drive but see LiveCD for an
alternative approach)

SOFTWARE REQUIREMENT :
Operating System- Ubuntu 16.04
Database- Mysql

OUTCOME : After completion of assignment student are able to implement database cursors
for merging two tables.

THEORY :
What is a Cursor?
For the processing of an SQL statement, the database needs to allocate memory. This memory is
known as the context area. The context area is a part of the PGA (Process Global Area) and is
allocated on the ORACLE Server. The memory structures SGA and PGA are explained in detail in
the chapter “ORACLE Architecture”.
A Cursor is associated with this work area (context area) used by ORACLE, for multi-row queries.
Here, ORACLE keeps track of row processing and related information.
A Cursor is a handle, or pointer to the context area. Using the cursor we can access the context
area. The cursor allows us to process the contents in the context area row by row and know some
information about it.

Types of Cursors
There are two types of cursors, explicit cursors and implicit cursors. Explicit cursors are defined
explicitly by the user in a PL/SQL block and implicit cursors are defined by ORACLE implicitly.
ORACLE defines implicit cursor for every SQL DML statement it processes.
Implicit Cursors
All the SQL DML statements or single row SELECT…INTO statements, are executed inside a
context area. During the processing, ORACLE implicitly defines a cursor that points to this
context area. It is known as a SQL cursor.

ORACLE implicitly
 Opens this SQL cursor ( memory is allocated and a set rows brought into the PGA),
 Processes the SQL statement in it ( processes the statement using rows), and
 Closes the cursor afterwards( de-allocating memory and making resources free).
The implicit cursor cannot be used by the user for processing its contents. However, the user
can use the implicit cursor attributes to get the information about execution of the SQL
statement.

Implicit Cursor Attributes


The implicit cursor defined by PL/SQL is called as ‘SQL’. Although the OPEN, CLOSE and
FETCH statements (as they are used with explicit cursors) cannot be used to manipulate the
SQL cursor, the cursor attributes can be used to access its context area.
The SQL cursor attributes always refer to the result of last SQL statement executed. The
following four cursor attributes can be used to access the SQL cursor’s context area.

%FOUND
%NOTFOUND
%ISOPEN
%ROWCOUNT
Explicit Cursors
These are user-defined cursors. Explicit cursors are defined in the declaration section of the
PL/SQL block. Explicit cursor manipulation is done through OPEN, FETCH, CLOSE Statements.
Explicit cursor information can be accessed using its attributes. There are four steps in which the
explicit cursor is processed
 Declaring a cursor
 Opening a cursor
 Fetching rows from an opened cursor
 Closing a cursor

EXECUTION STEPS :

EXECUTION STEPS :
Enter password: ******

Welcome to the MySQL monitor. Commands end with ; or \g.

Your MySQL connection id is 1

Server version: 5.1.45-community MySQL Community Server (GPL)

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

mysql> create database studentdata;

Query OK, 1 row affected (0.09 sec)

mysql> create table O_Rollcall(roll_no int,name varchar(20));

ERROR 1046 (3D000): No database selected

mysql> use studentdata;

Database changed

mysql> create table O_Rollcall(roll_no int,name varchar(20));

Query OK, 0 rows affected (0.16 sec)

mysql> insert into O_Rollcall values(2,'Aparna');

Query OK, 1 row affected (0.07 sec)

mysql> insert into O_Rollcall values(4,'maan');

Query OK, 1 row affected (0.00 sec)

mysql> insert into O_Rollcall values(5,'tips');

Query OK, 1 row affected (0.06 sec)

mysql> insert into O_Rollcall values(7,'Sneha');

Query OK, 1 row affected (0.08 sec)

mysql> insert into O_Rollcall values(8,'chotu');

Query OK, 1 row affected (0.00 sec)

mysql> select * from O_Rollcall;

+---------+--------+

| roll_no | name |

+---------+--------+
| 2 | Aparna |

| 4 | maan |

| 5 | tips |

| 7 | Sneha |

| 8 | chotu |

+---------+--------+

5 rows in set (0.17 sec)

mysql> create table N_Rollcall(roll_no int,name varchar(20));

Query OK, 0 rows affected (0.06 sec)

mysql> insert into N_Rollcall values(2,'Asha');

Query OK, 1 row affected (0.01 sec)

DROP PROCEDURE IF EXISTS proc_merge;


CREATE PROCEDURE proc_merge(IN inrn INT UNSIGNED)
BEGIN
DECLARE v_nm VARCHAR(50);
DECLARE rollno INT;
DECLARE rno INT;
DECLARE v_finished INT DEFAULT 0;
DECLARE cur_2 CURSOR FOR SELECT roll_no FROM N_Rollcall where roll_no=inrn;
DECLARE cur_1 CURSOR FOR SELECT roll_no,name FROM O_Rollcall where roll_no=inrn;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET v_finished = 1;
OPEN cur_1;
OPEN cur_2;
get_emp: LOOP
FETCH cur_1 into rollno,v_nm;
FETCH cur_2 into rno;
IF rno IS NULL THEN
select rollno,v_nm,rno;
insert into N_Rollcall values(rollno,v_nm);
END IF;
IF v_finished = 1 THEN
LEAVE get_emp;
END IF;
END LOOP get_emp;
CLOSE cur_1;
CLOSE cur_2;
END; $$

mysql>delimiter $$;

mysql> DROP PROCEDURE IF EXISTS proc_merge;


-> CREATE PROCEDURE proc_merge(IN inrn INT UNSIGNED)

-> BEGIN

-> DECLARE v_nm VARCHAR(50);

-> DECLARE rollno INT;

-> DECLARE rno INT;

-> DECLARE v_finished INT DEFAULT 0;

-> DECLARE cur_2 CURSOR FOR SELECT roll_no FROM N_Rollcall where roll_no=inr

n;

-> DECLARE cur_1 CURSOR FOR SELECT roll_no,name FROM O_Rollcall where roll_n

o=inrn;

-> DECLARE CONTINUE HANDLER FOR NOT FOUND SET v_finished = 1;

-> OPEN cur_1;

-> OPEN cur_2;

-> get_emp: LOOP

-> FETCH cur_1 into rollno,v_nm;

-> FETCH cur_2 into rno;

-> IF rno IS NULL THEN

-> select rollno,v_nm,rno;

-> insert into N_Rollcall values(rollno,v_nm);

-> END IF;

-> IF v_finished = 1 THEN

-> LEAVE get_emp;

-> END IF;

-> END LOOP get_emp;

-> CLOSE cur_1;

-> CLOSE cur_2;

-> END; $$
Query OK, 0 rows affected (0.00 sec)

mysql> Call proc_merge(2);$$

Query OK, 0 rows affected (0.00 sec)

mysql> Call proc_merge(4);$$

+--------+--------+------+

| rollno | v_nm | rno |

+--------+--------+------+

| 4 | maan | NULL |

+--------+--------+------+

1 row in set (0.00 sec)

Query OK, 1 row affected (0.05 sec)

mysql> Call proc_merge(5);$$

+--------+-------+------+

| rollno | v_nm | rno |

+--------+-------+------+

| 5 | tips | NULL |

+--------+-------+------+

1 row in set (0.00 sec)

Query OK, 1 row affected (0.01 sec)

mysql> Call proc_merge(8);$$

+--------+--------+------+

| rollno | v_nm | rno |

+--------+--------+------+

| 8 | chotu | NULL |

+--------+--------+------+
1 row in set (0.00 sec)

Query OK, 1 row affected (0.05 sec)

mysql> Call proc_merge(2);$$

Query OK, 0 rows affected (0.00 sec)

mysql> Select * from N_Rollcall;$$

+---------+--------+

| roll_no | name |

+---------+--------+

| 2 | Aparna |

| 7 | Sneha |

| 4 | maan |

| 5 | tips |

| 8 | chotu |

+---------+--------+

5 rows in set (0.00 sec)

Query OK, 0 rows affected (0.07 sec)

mysql> Call proc_merge(7);$$

+--------+--------+------+

| rollno | v_nm | rno |

+--------+--------+------+

| 7 | Sneha | NULL |

+--------+--------+------+

1 row in set (0.18 sec)

Query OK, 1 row affected (0.18 sec)

mysql> Select * from N_Rollcall;$$

+---------+--------+

| roll_no | name |
+---------+--------+

| 2 | Aparna |

| 7 | Sneha |

+---------+--------+

2 rows in set (0.00 sec)

CONCLUSION : Student successfully implemented database cursors for merging two tables.
GROUP A

EXPERIMENT 7

OBJECTIVE : To study and implement PL/SQL Stored Procedure and Stored Function

PROBLEM STATEMENT: 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.

HARDWARE REQUIREMENT :

2 GHz dual core processor.


2 GiB RAM (system memory)
25 GB of hard-drive space (or USB stick, memory card or external drive but see LiveCD for an
alternative approach)

SOFTWARE REQUIREMENT :
Operating System- Ubuntu 16.04
Database- Mysql

THEORY :
Subprogram Types
There are two types of subprogram:
• Procedures
• Functions
Procedures and functions both are PL/SQL programs addressed by name. They are stored on the
ORACLE Server in the form of compiled code, called as the p-code. Once a subprogram is created,
different ORACLE products and applications can reference it.

Procedures
A procedure is a subprogram that performs a specific action or task. A procedure has two parts
 The procedure specification
 The procedure body
The procedure specification specifies the procedure name and the parameters it accepts. It is not
necessary to create a procedure that accepts parameters.
The procedure body contains the declarative section without DECLARE keyword, the executable
section and an exception handling section.

Creating a procedure
The general syntax for procedure creation is
CREATE [ OR REPLACE ] PROCEDURE procedure_name
[ ( argument1 [ IN / OUT / IN OUT ] type ) ,
( argument2 [ IN / OUT / IN OUT ] type ) ,
...]
IS / AS
procedure_body

Where,
 procedure_name - is the name of the procedure to be created
 argument - is the name of the procedure parameter
 type - is the data type of the associated parameter
 procedure_body - is a PL/SQL block that makes up the code of the procedure.

Functions
A function is a subprogram, which is used to compute values and in many respects function is similar
to a procedure. Function also takes arguments and can be in different modes. Function also can be
stored in the database. It is a PL/SQL block consisting of declarative, executable, and exception
section.
The main difference in the procedure and a function is that the procedure call is a PL/SQL statement
by itself, while a function call is called as a part of an expression.Creating a Function
The general syntax for creation of function is.
CREATE OR REPLACE FUNCTION function_name
[ ( argument1 [ IN / OUT / IN OUT ] type ) ,
( argument2 [ IN / OUT / IN OUT ] type ) ,
...]
RETURN return_type IS / AS function_body

Where,
 function_name - is the name of the function to be created
 argument - is the name of the function parameter
 type - is the data type of the associated parameter
 return_type - is the type of the value that the function returns
 function_body - is a PL/SQL block containing the code for the function.
Similar to procedures, the argument list is optional. The function return type is required, since the
function call is a part of an expression. The return type of the function is used to determine the
type of the expression containing the function call.

The RETURN statement


Inside the body of a function, the RETURN statement is used to return control to the calling
environment with a value. The general syntax of the RETURN statement is
RETURN expression ;
where
 expression - is the value to be returned.
When the RETURN statement is executed, the control immediately returns to the calling
environment.

EXECUTION STEPS : MariaDB [Result]> delimiter $$

MariaDB [Result]> create procedure p (IN roll_no integer,IN name varchar(20),In total_marks
integer)

-> begin

-> declare grade varchar(20);

-> IF total_marks<=1500 and total_marks>=990 THEN

-> set grade:='DISTINCTION';

-> ELSEIF total_marks>=989 and total_marks<=900 THEN

-> set grade:='FIRST CLASS';

-> END IF;

-> insert into stu_marks values(name,total_marks);

-> insert into result values(roll_no,name,grade);

-> end;

-> $$

Query OK, 0 rows affected (0.00 sec)

MariaDB [Result]> call p(1,'Trupti','1450');

-> $$

Query OK, 1 row affected (0.03 sec)

MariaDB [Result]> call p(1,'Neha','1450')$$


Query OK, 1 row affected (0.03 sec)

MariaDB [Result]> call p(1,'sneha','1450')$$

Query OK, 1 row affected (0.03 sec)

select * from result;

-> $$

+---------+-------+-------------+

| roll_no | name | grade |

+---------+-------+-------------+

| NULL | NULL | NULL |

| 1 | Trupti| DISTINCTION

|2 |Neha|FIRST CLASS |

| 3 |sneha |DISTINCTION

+---------+-------+-------------+

4 rows in set (0.00 sec)

MariaDB [Result]> select * from stu_marks$$

+-------+-------------+

| name | total_marks |

+-------+-------------+

| NULL | NULL |

| Trupti | 1450 |

|Neha | 978 |

|sneha | 1100 |
+-------+-------------+

4 rows in set (0.00 sec)

OUTCOME : After completion of assignment student are able to implement PL/SQL Stored
Procedure to calculate student grade.

CONCLUSION : Student successfully implemented assignment to calculate students grade


using PL/SQL Stored Procedure .
GROUP A

EXPERIMENT 8

OBJECTIVE : To study and implement Database Trigger (All Types: Row level and Statement
level triggers, Before and After Triggers).

PROBLEM STATEMENT: 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.

HARDWARE REQUIREMENT :

2 GHz dual core processor.


2 GiB RAM (system memory)
25 GB of hard-drive space (or USB stick, memory card or external drive but see LiveCD for an
alternative approach)

SOFTWARE REQUIREMENT :
Operating System- Ubuntu 16.04
Database- Mysql

OUTCOME : After completion of assignment student are able to implement Database Trigger
(All Types: Row level and Statement level triggers, Before and After Triggers) for maintaining
library logs.

THEORY :
What are Database Triggers?
A database trigger is a PL/SQL program unit that is associated with a specific table. Triggers
can be used for purposes like auditing, implementing additional security. Triggers are
associated with a specific table and are fired automatically whenever the table gets
manipulated in a predefined way. The act of executing a trigger is called as firing a trigger.
Triggers are similar to procedures, in that they are named PL/SQL blocks with declarative,
executable, and exception-handling sections. However there are some differences between a
trigger and a procedure.
A procedure is executed explicitly from another block via a procedure call but a trigger is
executed implicitly whenever the triggering event happens. A procedure can also pass
arguments, but a trigger doesn’t accept arguments.
A database trigger has got the following components
• A triggering Event
• A triggering Constraint
• A triggering Action
Uses of Triggers
A trigger is fired automatically whenever any user or application modifies the associated
table in a predefined way. Triggers behave uniformly with respect to all users and
applications.
A Trigger can be utilized for
• Enforcing complex business rules - Triggers can be used to implement complex
integrity constraints not possible through declarative constraints in table creation.
• Audit Operations - Auditing information in a table by recording the changes made and
who made them. Since, triggers are executed automatically you can use triggers to log
events transparently based on DML operations.
• Maintain replicate tables / signaling other tables - Triggers can be used for
automatically signaling other programs that action needs to take place when changes are
made to the table.
• Computing values - A trigger can be used to derive column values automatically during
a data manipulation operation.
• Security - Triggers can be used to implement complex security authorizations.

Trigger categories
Triggers are categorised in various ways. Trigger are categorised using
• Trigger Type
• Triggering Time
• Triggering Event

Trigger Types
There are two types of triggers
 Statement Trigger
 Row Trigger

Statement Trigger
A Statement Trigger is a trigger in which the trigger action is executed once for the
manipulation operation that fires the trigger. You can use a statement trigger when
the trigger action is independent of the data provided by the operation that fires the
trigger and/or the affected rows.
Example: a statement trigger can be used to maintain the log of operation on a
particular table.

Row Trigger
A Row Trigger is a trigger in which the trigger action is performed repeatedly for
each row of the table that is affected by the manipulation operation that fires the
trigger. You use a row trigger when the trigger action is dependent on the data
provided by the operation that fires the trigger and/or the accented rows.
For example, a row level trigger can be used for maintaining the consolidated balance
with each transaction.
Triggering Time
Triggers can specify the time of trigger action. Possible options for the time of a trigger
action are
 BEFORE the triggering event
 AFTER the triggering event

Before Trigger
The trigger action is performed before the operation that fires the trigger is executed.
This trigger is used when execution of operation depends on trigger action. For
example, in a bank account, before debiting an account, checking whether the current
balance is greater than the amount to be debited.

After Trigger
The trigger action is performed after the operation that fires the trigger is executed.
This trigger is used when triggering action depends on the execution of operation. For
example, in a bank account, updating balance after debiting or crediting an account.

Triggering Events
Triggering events are the DML operations. These operations are
 Insert
 Update
 Delete
When these operations are performed on a table, the trigger, which is associated with the
operation, is fired. Triggering events divide triggers into these three types
 DELETE TRIGGER
 INSERT TRIGGER
 UPDATE TRIGGER

EXECUTION STEPS :

MariaDB [(none)]> use library

Database changed

MariaDB [library]> create table library(b_no int,b_name varchar(50),author


varchar(50),allowed_days int);

Query OK, 0 rows affected (0.09 sec)

MariaDB [library]> insert into library values(1,"Java","tips","20");


Query OK, 1 row affected (0.02 sec)

MariaDB [library]> insert into library values(2,"C++","appy","33");

Query OK, 1 row affected (0.02 sec)

MariaDB [library]> insert into library values(3,"Basic C","maan","23");

Query OK, 1 row affected (0.01 sec)

MariaDB [library]> insert into library values(4,"Android","sanedo","45");

Query OK, 1 row affected (0.01 sec)

MariaDB [library]> insert into library values(5,"Stress Handling","akash","30");

Query OK, 1 row affected (0.01 sec)

MariaDB [library]> select * from library;

+------+-----------------+-----------+--------------+

| b_no | b_name | author | allowed_days |

+------+-----------------+-----------+--------------+

| 1 | Java | tips | 20 |

| 2 | C++ | appy | 33 |

| 3 | Basic C | maan | 23 |

| 4 | Android | sanedo | 45 |

| 5 | Stress Handling | akash | 30 |

+------+-----------------+-----------+--------------+

5 rows in set (0.00 sec)


MariaDB [library]> create table Lib_audit(b_no int,old_allowed_days int,new_alldays int);

Query OK, 0 rows affected (0.06 sec)

MariaDB [library]> update library set allowed_days=60 where b_no=3;

Query OK, 1 row affected (0.03 sec)

Rows matched: 1 Changed: 1 Warnings: 0

MariaDB [library]> update library set allowed_days=40 where b_no=4;

Query OK, 1 row affected (0.02 sec)

Rows matched: 1 Changed: 1 Warnings: 0

MariaDB [library]> describe Lib_audit

-> $$

+------------------+---------+------+-----+---------+-------+

| Field | Type | Null | Key | Default | Extra |

+------------------+---------+------+-----+---------+-------+

| b_no | int(11) | YES | | NULL | |

| old_allowed_days | int(11) | YES | | NULL | |

| new_alldays | int(11) | YES | | NULL | |

+------------------+---------+------+-----+---------+-------+

3 rows in set (0.02 sec)

MariaDB [library]> create trigger t1 before update on library for each row begin insert into
Lib_audit values(b_no,old.allowed_days,new.allowed_days); end;$$
Query OK, 0 rows affected (0.07 sec)

MariaDB [library]> select * from Lib_audit;

-> $$

Empty set (0.01 sec)

MariaDB [library]> select * from Lib_audit;

-> $$

Empty set (0.00 sec)

MariaDB [library]> select * from library;

-> $$

+------+-----------------+-----------+--------------+

| b_no | b_name | author | allowed_days |

+------+-----------------+-----------+--------------+

| 1 | Java | tips | 20 |

| 2 | C++ | appy | 33 |

| 3 | Basic C | maan | 60 |

| 4 | Android | sanedo | 40 |

| 5 | Stress Handling | akash | 30 |

+------+-----------------+-----------+--------------+

5 rows in set (0.01 sec)

MariaDB [library]> update library set allowed_days=60 where b_no=2;

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

Rows matched: 1 Changed: 1 Warnings: 0

MariaDB [library]> select * from library;

-> $$

+------+-----------------+-----------+--------------+

| b_no | b_name | author | allowed_days |

+------+-----------------+-----------+--------------+

| 1 | Java | tips | 20 |

| 2 | C++ | appy | 60 |

| 3 | Basic C | maan | 60 |

| 4 | Android | sanedo | 40 |

| 5 | Stress Handling | akash | 30 |

+------+-----------------+-----------+--------------+

5 rows in set (0.00 sec)

MariaDB [library]> select * from Lib_audit;

-> $$

+------+------------------+-------------+

| b_no | old_allowed_days | new_alldays |

+------+------------------+-------------+

| NULL | 33 | 60 |

+------+------------------+-------------+

1 row in set (0.00 sec)

MariaDB [library]> create trigger t2 after delete on library for each row begin insert into
Lib_audit values(old.b_no,old.allowed_days,old.allowed_days); end;$$

Query OK, 0 rows affected (0.07 sec)

MariaDB [library]> select * from library;

-> $$

+------+-----------------+-----------+--------------+

| b_no | b_name | author | allowed_days |

+------+-----------------+-----------+--------------+

| 1 | Java | tips | 20 |

| 2 | C++ | appy | 60 |

| 3 | Basic C | maan | 60 |

| 4 | Android | sanedo | 40 |

| 5 | Stress Handling | akash | 30 |

+------+-----------------+-----------+--------------+

5 rows in set (0.00 sec)

MariaDB [library]> delete from library where b_no=1;

-> $$

Query OK, 1 row affected (0.04 sec)

MariaDB [library]> select * from library;

-> $$

+------+-----------------+-----------+--------------+

| b_no | b_name | author | allowed_days |

+------+-----------------+-----------+--------------+

| 2 | C++ | appy | 60 |

| 3 | Basic C | maan | 60 |
| 4 | Android | sanedo | 40 |

| 5 | Stress Handling | akash | 30 |

+------+-----------------+-----------+--------------+

4 rows in set (0.00 sec)

MariaDB [library]> select * from Lib_audit;

-> $$

+------+------------------+-------------+

| b_no | old_allowed_days | new_alldays |

+------+------------------+-------------+

| NULL | 33 | 60 |

| 1| 20 | 20 |

+------+------------------+-------------+

2 rows in set (0.00 sec)

CONCLUSION : Students successfully implemented trigger to calculate library audit log.


GROUP B

EXPERIMENT 9

OBJECTIVE : Study of Open Source NOSQL Database: MongoDB installation.

PROBLEM STATEMENT: Study of Open Source NOSQL Database: MongoDB (Installation,


Basic CRUD operations, Execution)

HARDWARE REQUIREMENT :

2 GHz dual core processor.


2 GB RAM (system memory)
25 GB of hard-drive space (or USB stick, memory card or external drive but see LiveCD for an
alternative approach)

SOFTWARE REQUIREMENT :
Operating System- Ubuntu 16.04
Database- Mongo DB

OUTCOME :After completion of assignment student are able to install Open Source NOSQL
Database: Mongo DB .

THEORY :
MongoDB is one of several database types to arise in the mid-2000s under the NoSQLbanner.
Instead of using tables and rows as in relational databases, MongoDB is built on an architecture
of collections and documents. Documents comprise sets of key-value pairs and are the basic unit
of data in MongoDB. Collections contain sets of documents and function as the equivalent of
relational database tables. Like other NoSQL databases, MongoDB supports
dynamic schema design, allowing the documents in a collection to have different fields and
structures. The database uses a document storage and data interchange format called BSON,
which provides a binary representation of JSON-like documents. Automatic shardingenables
data in a collection to be distributed across multiple systems for horizontal scalabilityas
data volumes increase.
Mongo DB was created by Dwight Merriman and Eliot Horowitz, who had encountered
development and scalability issues with traditional relational database approaches while
building Web applications at DoubleClick, an Internet advertising company that is now owned
by Google Inc. According to Merriman, the name of the database was derived from the
word humongous to represent the idea of supporting large amounts of data. Merriman and
Horowitz helped form 10Gen Inc. in 2007 to commercialize MongoDB and related software. The
company was renamed MongoDB Inc. in 2013.
The database was released to open source in 2009 and is available under the terms of the Free
Software Foundation's GNU AGPL Version 3.0 commercial license. At the time of this writing,
among other users, the insurance company MetLife is using MongoDB for customer service
applications, the website Craigslist is using it for archiving data, the CERN physics lab is using it
for data aggregation and discovery and the The New York Times newspaper is using MongoDB
to support a form-building application for photo submissions

EXECUTION STEPS :

Download Mongodb .Jar file for Linux from URL :

https://www.mongodb.com/download-center#atlas

Extract in home folder.

On First Terminal

[student@localhost mongodb]$ cd mongodb-linux-x86_64-2.6.1/

[student@localhost bin]$ ./mongod --dbpath /home/student/mongodb/mydata

2014-07-12T10:23:55.063+0530 [initandlisten] MongoDB starting : pid=6634 port=27017


dbpath=/home/student/mongodb/mydata 64-bit host=localhost.localdomain

2014-07-12T10:23:55.063+0530 [initandlisten] db version v2.6.1

2014-07-12T10:23:55.063+0530 [initandlisten] git version:


4b95b086d2374bdcfcdf2249272fb552c9c726e8

2014-07-12T10:23:55.063+0530 [initandlisten] build info: Linux build14.nj1.10gen.cc 2.6.32-


431.3.1.el6.x86_64 #1 SMP Fri Jan 3 21:39:27 UTC 2014 x86_64
BOOST_LIB_VERSION=1_49

2014-07-12T10:23:55.063+0530 [initandlisten] allocator: tcmalloc

2014-07-12T10:23:55.063+0530 [initandlisten] options: { storage: { dbPath:


"/home/student/mongodb/mydata" } }

2014-07-12T10:23:55.109+0530 [initandlisten] journal


dir=/home/student/mongodb/mydata/journal

On second terminal:
[student@localhost ~]$ cd /home/student/mongodb/mongodb-linux-x86_64-2.6.1

[student@localhost mongodb-linux-x86_64-2.6.1]$ cd bin

[student@localhost bin]$ ./mongo


MongoDB shell version: 2.6.1

connecting to: test

Welcome to the MongoDB shell.

For interactive help, type "help".

For more comprehensive documentation, see

http://docs.mongodb.org/

Questions? Try the support group

http://groups.google.com/group/mongodb-user

>

CONCLUSION : Students successfully install Open Source NOSQL Database: MongoDB .


GROUP B

EXPERIMENT 10

OBJECTIVE : To Design and Develop MongoDB Queries using CRUD operations.

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

HARDWARE REQUIREMENT :

2 GHz dual core processor.


2 GiB RAM (system memory)
25 GB of hard-drive space (or USB stick, memory card or external drive but see LiveCD for an
alternative approach)

SOFTWARE REQUIREMENT :
Operating System- Ubuntu 16.04
Database- Mongo DB

OUTCOME :After completion of assignment student are able to Design and Develop Mongo
DB Queries using CRUD operations.

THEORY :
Basic Operations with the Shell: We can use the four basic operations, create, read, update and
delete (CRUD) to manipulate and view data in the shell.

1.Create:-The insert function adds a document to a collection.

2. Read:- Find and find One can be used to query a collection. If we just want to see one
document from a collection, we can use find One. Find and find One can also be passed criteria
in the form of a query document. This will restrict the documents matched by the query. The
shell will automatically display up to 20 documents matching a find, but more can be fetched.

3. Update:- If we would like to modify our post, we can use update. Update takes (at least) two
parameters: the first is the criteria to find which document to update, and the second is the new
document. Suppose we decide to enable comments on the blog post we created earlier. We’ll
need to add an array of comments as the value for a new key in our document.

4.Delete:- Remove permanently deletes documents from the database. Called with no
parameters, it removes all documents from a collection. It can also take a document specifying
criteria for removal.

5.fsync:- Mongo DBs fsync command allows us to copy the data directory of a running Mongo
DB server without risking any corruption. The fsync command will force the MongoDB server
to flush all pending writes to disk. It will also, optionally, hold a lock preventing any further
writes to the database until the server is unlocked.

6. Unlock:- After performing the backup, we need to unlock the database again: Simultaneously
if connection terminal is open you can see changes over their while running this command.

7. touch:-The touch command loads data from the data storage layer into memory. touch can
load the data (i.e. documents) indexes or both documents and indexes. Use this command to
ensure that a collection, and/or its indexes, are in memory before another operation. By loading
the collection or indexes into memory, mongod will ideally be able to perform subsequent
operations more efficiently.

EXECUTION STEPS :
[bvcoew@localhost bin]$ cd mongodb-linux-x86_64-2.6.1
bash: cd: mongodb-linux-x86_64-2.6.1: No such file or directory
[bvcoew@localhost bin]$ file:///home/bvcoew/mongodb-linux-x86_64-2.6.1.tgz
bash: file:///home/bvcoew/mongodb-linux-x86_64-2.6.1.tgz: No such file or directory
[bvcoew@localhost bin]$ cd file:///home/bvcoew/mongodb-linux-x86_64-2.6.1.tgz
bash: cd: file:///home/bvcoew/mongodb-linux-x86_64-2.6.1.tgz: No such file or directory
[bvcoew@localhost bin]$ cd file:///home/bvcoew/mongodb-linux-x86_64-2.6.1.tgz
bash: cd: file:///home/bvcoew/mongodb-linux-x86_64-2.6.1.tgz: No such file or directory
[bvcoew@localhost bin]$ ./mongo
MongoDB shell version: 2.6.1
connecting to: test
> show dbs
admin (empty)
college 0.078GB
engg 0.078GB
local 0.078GB
> use db try
2014-07-21T13:53:46.511+0530 Error: [db try] is not a valid database name at
src/mongo/shell/mongo.js:41

1)create database student for student name,id,branch,class:


> use student
switched to db student
> db.stud.insert({'name':'siddhi','id':123,'branch':'comp','class':'te'});
WriteResult({ "nInserted" : 1 })
> db.stud.insert({'name':'shruti','id':12343,'branch':'comp','class':'te'});
WriteResult({ "nInserted" : 1 })
> db.stud.insert({'name':'palak','id':12345,'branch':'comp','class':'te'});
WriteResult({ "nInserted" : 1 })
> db.stud.insert({'name':'pooja','id':12345,'branch':'comp','class':'te'});
WriteResult({ "nInserted" : 1 })
> db.stud.insert({'name':'payal','id':123456,'branch':'comp','class':'te'});
WriteResult({ "nInserted" : 1 })
> db.student.find().';
> db.stud.find();
{ "_id" : ObjectId("53ccced20a223f605a293d65"), "name" : "siddhi", "id" : 123, "branch" :
"comp", "class" : "te" }
{ "_id" : ObjectId("53ccceee0a223f605a293d66"), "name" : "shruti", "id" : 12343, "branch" :
"comp", "class" : "te" }
{ "_id" : ObjectId("53cccf030a223f605a293d67"), "name" : "palak", "id" : 12345, "branch" :
"comp", "class" : "te" }
{ "_id" : ObjectId("53cccf130a223f605a293d68"), "name" : "pooja", "id" : 12345, "branch" :
"comp", "class" : "te" }
{ "_id" : ObjectId("53cccf490a223f605a293d69"), "name" : "payal", "id" : 123456, "branch" :
"comp", "class" : "te" }

2)update address for id 1to 5 with city,street and pin code:

> db.std.update({ "_id" : ObjectId("53faef0e86280a0032e40ee6"), "name" : "siddhi", "id" : 1,


"branch" : "comp", "class" : "te" },{'$set':{'city':'pune','street':'abc','pin':411047}});
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.std.update({"id" : 2},{'$set':{'city':'mumbai','street':'abc','pin':411047}});
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.std.update({"id" : 3},{'$set':{'city':'pune','street':'abc','pin':411047}});
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.std.update({"id" : 4},{'$set':{'city':'pune','street':'abc','pin':411047}});
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.std.update({"id" : 5},{'$set':{'city':'mumbai','street':'abc','pin':411047}});
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.std.find();
{ "_id" : ObjectId("53faef0e86280a0032e40ee6"), "name" : "siddhi", "id" : 1, "branch" : "comp",
"class" : "te", "city" : "pune", "street" : "abc", "pin" : 411047 }
{ "_id" : ObjectId("53faef2586280a0032e40ee7"), "name" : "bhargavi", "id" : 2, "branch" :
"comp", "class" : "te", "city" : "mumbai", "street" : "abc", "pin" : 411047 }
{ "_id" : ObjectId("53faef3686280a0032e40ee8"), "name" : "shraddha", "id" : 3, "branch" :
"comp", "class" : "te", "city" : "pune", "street" : "abc", "pin" : 411047 }
{ "_id" : ObjectId("53faef4586280a0032e40ee9"), "name" : "neha", "id" : 4, "branch" : "comp",
"class" : "te", "city" : "pune", "street" : "abc", "pin" : 411047 }
{ "_id" : ObjectId("53faef5186280a0032e40eea"), "name" : "shruti", "id" : 5, "branch" : "comp",
"class" : "te", "city" : "mumbai", "street" : "abc", "pin" : 411047 }

3)create a telephone array for 1 to 5id:

> db.std.update({'id':1},{ $set: {'telephone':[99999999,1333955,576878]}})


WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.std.update({'id':2},{ $set: {'telephone':[99999999,1333955,576878]}})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.std.update({'id':3},{ $set: {'telephone':[99999999,1333955,576878]}})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.std.update({'id':4},{ $set: {'telephone':[99999999,1333955,576878]}})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.std.update({'id':5},{ $set: {'telephone':[99999999,1333955,576878]}})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.std.find();
{ "_id" : ObjectId("53faef0e86280a0032e40ee6"), "name" : "siddhi", "id" : 123, "branch" :
"comp", "class" : "te", "address" : "pune", "city" : "pune", "street" : "abc", "pin" : 123456,
"telephone" : [ 99999999, 1333955, 576878 ] }
{ "_id" : ObjectId("53faef2586280a0032e40ee7"), "name" : "pooja", "id" : 12345, "branch" :
"comp", "class" : "te", "city" : "pune", "street" : "abc", "pin" : 123456, "telephone" : [ 99999999,
1333955, 576878 ] }
{ "_id" : ObjectId("53faef3686280a0032e40ee8"), "name" : "palak", "id" : 12345, "branch" :
"comp", "class" : "te", "city" : "pune", "street" : "abc", "pin" : 123456, "telephone" : [ 99999999,
1333955, 576878 ] }
{ "_id" : ObjectId("53faef4586280a0032e40ee9"), "name" : "shruti", "id" : 12343, "branch" :
"comp", "class" : "te", "city" : "pune", "street" : "abc", "pin" : 123456, "telephone" : [ 99999999,
1333955, 576878 ] }
{ "_id" : ObjectId("53faef5186280a0032e40eea"), "name" : "payal", "id" : 123456, "branch" :
"comp", "class" : "te", "city" : "mobaie", "street" : "abc", "pin" : 123456, "telephone" :
[ 99999999, 1333955, 576878 ] }

4)list student with pune city:

>db.std.find({'city':'pune'})
{ "_id" : ObjectId("53faef0e86280a0032e40ee6"), "name" : "siddhi", "id" : 1, "branch" : "comp",
"class" : "te", "city" : "pune", "street" : "abc", "pin" : 411047,"telephone" : [ 99999999, 1333955,
576878 ] }
{ "_id" : ObjectId("53faef3686280a0032e40ee8"), "name" : "shraddha", "id" : 3, "branch" :
"comp", "class" : "te", "city" : "pune", "street" : "abc", "pin" : 411047 ,"telephone" : [ 99999999,
1333955, 576878 ]}
{ "_id" : ObjectId("53faef4586280a0032e40ee9"), "name" : "neha", "id" : 4, "branch" : "comp",
"class" : "te", "city" : "pune", "street" : "abc", "pin" : 411047 ,"telephone" : [ 99999999,
1333955, 576878 ]}

5)list with name start s:

> db.std.find({'name':{ $regex: 's'}})


{ "_id" : ObjectId("53faef0e86280a0032e40ee6"), "name" : "siddhi", "id" : 1, "branch" : "comp",
"class" : "te", "city" : "pune", "street" : "abc", "pin" : 411047 ,"telephone" : [ 99999999,
1333955, 576878 ]}
{ "_id" : ObjectId("53faef3686280a0032e40ee8"), "name" : "shraddha", "id" : 3, "branch" :
"comp", "class" : "te", "city" : "pune", "street" : "abc", "pin" : 411047 ,"telephone" : [ 99999999,
1333955, 576878 ]}
{ "_id" : ObjectId("53faef5186280a0032e40eea"), "name" : "shruti", "id" : 5, "branch" : "comp",
"class" : "te", "city" : "mumbai", "street" : "abc", "pin" : 411047 ,"telephone" : [ 99999999,
1333955, 576878 ]}

6)update with id 5 with new name branch class

> db.std.update({'name':'shruti'},{ $set: {'name':'john','branch':'it','class':'be'}})


WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.std.find();
{ "_id" : ObjectId("53faef0e86280a0032e40ee6"), "name" : "siddhi", "id" : 1, "branch" : "comp",
"class" : "te", "city" : "pune", "street" : "abc", "pin" : 411047 }
{ "_id" : ObjectId("53faef2586280a0032e40ee7"), "name" : "bhargavi", "id" : 2, "branch" :
"comp", "class" : "te", "city" : "mumbai", "street" : "abc", "pin" : 411047 }
{ "_id" : ObjectId("53faef3686280a0032e40ee8"), "name" : "shraddha", "id" : 3, "branch" :
"comp", "class" : "te", "city" : "pune", "street" : "abc", "pin" : 411047 }
{ "_id" : ObjectId("53faef4586280a0032e40ee9"), "name" : "neha", "id" : 4, "branch" : "comp",
"class" : "te", "city" : "pune", "street" : "abc", "pin" : 411047 }
{ "_id" : ObjectId("53faef5186280a0032e40eea"), "name" : "john", "id" : 5, "branch" : "it",
"class" : "be", "city" : "mumbai", "street" : "abc", "pin" : 411047 }

7)add subject array for three subject:

> db.std.update({'name':'siddhi'},{ $set: {'sub':['dc','osd','fca']}})


WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.std.update({'name':'bhargavi'},{ $set: {'sub':['dc','osd','fca']}})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.std.update({'name':'shraddha'},{ $set: {'sub':['dc','osd','fca']}})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.std.update({'name':'neha'},{ $set: {'sub':['dc','osd','fca']}})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.std.update({'name':'john'},{ $set: {'sub':['dc','osd','fca']}})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.std.find();
{ "_id" : ObjectId("53faef0e86280a0032e40ee6"), "name" : "siddhi", "id" : 1, "branch" : "comp",
"class" : "te", "city" : "pune", "street" : "abc", "pin" : 411047, "sub" : [ "dc", "osd", "fca" ] }
{ "_id" : ObjectId("53faef2586280a0032e40ee7"), "name" : "bhargavi", "id" : 2, "branch" :
"comp", "class" : "te", "city" : "mumbai", "street" : "abc", "pin" : 411047, "sub" : [ "dc", "osd",
"fca" ] }
{ "_id" : ObjectId("53faef3686280a0032e40ee8"), "name" : "shraddha", "id" : 3, "branch" :
"comp", "class" : "te", "city" : "pune", "street" : "abc", "pin" : 411047, "sub" : [ "dc", "osd",
"fca" ] }
{ "_id" : ObjectId("53faef4586280a0032e40ee9"), "name" : "neha", "id" : 4, "branch" : "comp",
"class" : "te", "city" : "pune", "street" : "abc", "pin" : 411047, "sub" : [ "dc", "osd", "fca" ] }
{ "_id" : ObjectId("53faef5186280a0032e40eea"), "name" : "john", "id" : 5, "branch" : "it",
"class" : "be", "city" : "mumbai", "street" : "abc", "pin" : 411047, "sub" : [ "dc", "osd", "fca" ] }
8)increment marks of id 5 of subject 1

> db.std.update({'id':5},{ $inc:{'dc':10}});


WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.std.find();
{ "_id" : ObjectId("53faef0e86280a0032e40ee6"), "name" : "siddhi", "id" : 1, "branch" : "comp",
"class" : "te", "city" : "pune", "street" : "abc", "pin" : 411047, "sub" : [ "dc", "osd", "fca" ], "dc" :
10 }
{ "_id" : ObjectId("53faef2586280a0032e40ee7"), "name" : "bhargavi", "id" : 2, "branch" :
"comp", "class" : "te", "city" : "mumbai", "street" : "abc", "pin" : 411047, "sub" : [ "dc", "osd",
"fca" ] }
{ "_id" : ObjectId("53faef3686280a0032e40ee8"), "name" : "shraddha", "id" : 3, "branch" :
"comp", "class" : "te", "city" : "pune", "street" : "abc", "pin" : 411047, "sub" : [ "dc", "osd",
"fca" ] }
{ "_id" : ObjectId("53faef4586280a0032e40ee9"), "name" : "neha", "id" : 4, "branch" : "comp",
"class" : "te", "city" : "pune", "street" : "abc", "pin" : 411047, "sub" : [ "dc", "osd", "fca" ] }
{ "_id" : ObjectId("53faef5186280a0032e40eea"), "name" : "john", "id" : 5, "branch" : "it",
"class" : "be", "city" : "mumbai", "street" : "abc", "pin" : 411047, "sub" : [ "dc", "osd", "fca" ],
"marks" : [ 20, 30, 40 ], "dc" : 10 }
> db.std.update({'id':5},{ $inc:{'dc':10}});
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.std.find();
{ "_id" : ObjectId("53faef0e86280a0032e40ee6"), "name" : "siddhi", "id" : 1, "branch" : "comp",
"class" : "te", "city" : "pune", "street" : "abc", "pin" : 411047, "sub" : [ "dc", "osd", "fca" ], "dc" :
10 }
{ "_id" : ObjectId("53faef2586280a0032e40ee7"), "name" : "bhargavi", "id" : 2, "branch" :
"comp", "class" : "te", "city" : "mumbai", "street" : "abc", "pin" : 411047, "sub" : [ "dc", "osd",
"fca" ] }
{ "_id" : ObjectId("53faef3686280a0032e40ee8"), "name" : "shraddha", "id" : 3, "branch" :
"comp", "class" : "te", "city" : "pune", "street" : "abc", "pin" : 411047, "sub" : [ "dc", "osd",
"fca" ] }
{ "_id" : ObjectId("53faef4586280a0032e40ee9"), "name" : "neha", "id" : 4, "branch" : "comp",
"class" : "te", "city" : "pune", "street" : "abc", "pin" : 411047, "sub" : [ "dc", "osd", "fca" ] }
{ "_id" : ObjectId("53faef5186280a0032e40eea"), "name" : "john", "id" : 5, "branch" : "it",
"class" : "be", "city" : "mumbai", "street" : "abc", "pin" : 411047, "sub" : [ "dc", "osd", "fca" ],
"marks" : [ 20, 30, 40 ], "dc" : 20 }

9)add state:

>db.std.update({'name':'siddhi'},{ $set: {'state':'maharashtra'}})


WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.std.update({'name':'bhargavi'},{ $set: {'state':'maharashtra'}})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.std.update({'name':'shraddha'},{ $set: {'state':'maharashtra'}})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.std.update({'name':'neha'},{ $set: {'state':'maharashtra'}})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.std.update({'name':'john'},{ $set: {'state':'maharashtra'}})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.std.find();
{ "_id" : ObjectId("53faef0e86280a0032e40ee6"), "name" : "siddhi", "id" : 1, "branch" : "comp",
"class" : "te", "city" : "pune", "street" : "abc", "pin" : 411047, "sub" : [ "dc", "osd", "fca" ],
"state" : "maharashtra" }
{ "_id" : ObjectId("53faef2586280a0032e40ee7"), "name" : "bhargavi", "id" : 2, "branch" :
"comp", "class" : "te", "city" : "mumbai", "street" : "abc", "pin" : 411047, "sub" : [ "dc", "osd",
"fca" ], "state" : "maharashtra" }
{ "_id" : ObjectId("53faef3686280a0032e40ee8"), "name" : "shraddha", "id" : 3, "branch" :
"comp", "class" : "te", "city" : "pune", "street" : "abc", "pin" : 411047, "sub" : [ "dc", "osd",
"fca" ], "state" : "maharashtra" }
{ "_id" : ObjectId("53faef4586280a0032e40ee9"), "name" : "neha", "id" : 4, "branch" : "comp",
"class" : "te", "city" : "pune", "street" : "abc", "pin" : 411047, "sub" : [ "dc", "osd", "fca" ],
"state" : "maharashtra" }
{ "_id" : ObjectId("53faef5186280a0032e40eea"), "name" : "john", "id" : 5, "branch" : "it",
"class" : "be", "city" : "mumbai", "street" : "abc", "pin" : 411047, "sub" : [ "dc", "osd", "fca" ],
"state" : "maharashtra" }

10)remove state:

> db.std.update({'name':'siddhi'},{ $unset: {'state':'maharashtra'}})


WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.std.update({'name':'bhargavi'},{ $unset: {'state':'maharashtra'}})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.std.update({'name':'shraddha'},{ $unset: {'state':'maharashtra'}})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.std.update({'name':'neha'},{ $unset: {'state':'maharashtra'}})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.std.update({'name':'john'},{ $unset: {'state':'maharashtra'}})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.std.find();
{ "_id" : ObjectId("53faef0e86280a0032e40ee6"), "name" : "siddhi", "id" : 1, "branch" : "comp",
"class" : "te", "city" : "pune", "street" : "abc", "pin" : 411047, "sub" : [ "dc", "osd", "fca" ] }
{ "_id" : ObjectId("53faef2586280a0032e40ee7"), "name" : "bhargavi", "id" : 2, "branch" :
"comp", "class" : "te", "city" : "mumbai", "street" : "abc", "pin" : 411047, "sub" : [ "dc", "osd",
"fca" ] }
{ "_id" : ObjectId("53faef3686280a0032e40ee8"), "name" : "shraddha", "id" : 3, "branch" :
"comp", "class" : "te", "city" : "pune", "street" : "abc", "pin" : 411047, "sub" : [ "dc", "osd",
"fca" ] }
{ "_id" : ObjectId("53faef4586280a0032e40ee9"), "name" : "neha", "id" : 4, "branch" : "comp",
"class" : "te", "city" : "pune", "street" : "abc", "pin" : 411047, "sub" : [ "dc", "osd", "fca" ] }
{ "_id" : ObjectId("53faef5186280a0032e40eea"), "name" : "john", "id" : 5, "branch" : "it",
"class" : "be", "city" : "mumbai", "street" : "abc", "pin" : 411047, "sub" : [ "dc", "osd", "fca" ] }

11)remove document with name john:

> db.std.remove({'name':'john'})
WriteResult({ "nRemoved" : 1 })
> db.std.find();
{ "_id" : ObjectId("53faef0e86280a0032e40ee6"), "name" : "siddhi", "id" : 1, "branch" : "comp",
"class" : "te", "city" : "pune", "street" : "abc", "pin" : 411047, "sub" : [ "dc", "osd", "fca" ], "dc" :
10 }
{ "_id" : ObjectId("53faef2586280a0032e40ee7"), "name" : "bhargavi", "id" : 2, "branch" :
"comp", "class" : "te", "city" : "mumbai", "street" : "abc", "pin" : 411047, "sub" : [ "dc", "osd",
"fca" ] }
{ "_id" : ObjectId("53faef3686280a0032e40ee8"), "name" : "shraddha", "id" : 3, "branch" :
"comp", "class" : "te", "city" : "pune", "street" : "abc", "pin" : 411047, "sub" : [ "dc", "osd",
"fca" ] }
{ "_id" : ObjectId("53faef4586280a0032e40ee9"), "name" : "neha", "id" : 4, "branch" : "comp",
"class" : "te", "city" : "pune", "street" : "abc", "pin" : 411047, "sub" : [ "dc", "osd", "fca" ] }
>

CONCLUSION : Students successfully implemented CRUD operation in MongoDB.


GROUP B

EXPERIMENT 11

OBJECTIVE : To study and implement aggregation and indexing with suitable example using
Mongo DB.

PROBLEM STATEMENT: Implement aggregation and indexing with suitable example using
Mongo DB.

HARDWARE REQUIREMENT :

2 GHz dual core processor.


2 GiB RAM (system memory)
25 GB of hard-drive space (or USB stick, memory card or external drive but see LiveCD for an
alternative approach)

SOFTWARE REQUIREMENT :
Operating System- Ubuntu 16.04
Database- Mongo DB

OUTCOME : After completion of assignment student are able to indexing and aggregation in
mongo db.

THEORY :
AGGREGATION:

• Aggregate operation process data records and returns computed result.

• It group value from multiple document together and perform a varitey of operation on grouped
data to return a single result.

Aggregate Methods:

• It is used for performing aggregation operation.

Syntax:

db.Collection_Name.aggregate(AGGREGATE_CRITERIA)

-list of avaliable aggregation expression

• $sum

• $avg
• $min

• $max

• $push

• $addToSet

• $first

• $last

$avg:

calculate the average of all given values from all document in collection.

Example:

db.Teacher_Info.([{$group:{_id:”$by_user”;num_tutorial:{$avg:”$likes”}}}])

$push:

Insert the value of any array in the resulting document.

Example:

db.Teacher_Info.([{$group:{_id:”$by_user”;num_tutorial:{$push:”$num_tutorial”}}}])

$addToSet:

Insert the value to an array in the resulting document but dose not create duplicates.

Example:

db.Teacher_Info.([{$group:{_id:”$by_user”;url:{$addToSet:”$url”}}}])

modifiers:

• $set:

It set the value of a key.If the key dosent yet exist the it will be created

for example:

>db.user.update({”uid”:4},{”$set”:{”favourite book”:”war and peace”}})


It reset the value of existing key.

>db.user.update({”name”:”joe”},{”$unset”:{”favourite book”:”1”}})

INDEXING:

Indexes support the efficent resolution of queries.without indexes monodb must scan every
document of collection to select those document that match the query statment.This scan is
highly inefficent and requried the mongodb to process a large volume of data.

Indexes are special data structures that store a small portion of the data set in an easy to
transverse form.The index stores the value of specific field or set of fields,orderded by value of
field specified in index.

The ensureIndex() Method:

To create an index you need to use the ensureIndex() method of mongoDB

Syntax:

>db.COLLECTION_NAME.ensureIndex({key:1})

here is the name of the field on which you want to create index and 1 is for ascending order.To
create in descending order you need to use -1.

>db.Teacher_Info.ensureIndex({”Teacher_ID”:1})

In ensureIndex() method we can pass multiple fields to create index on multiple fields.

>db.Teacher_Info.ensureIndex({”Title”:1,”description”:-1})

ensureIndex() method also accepts list of options which list is given below:

• Parameter-Background

Type:Boolean

Description-Buids the index in the background so that building of inex dose not block other
building.An index does not block other database activites.specify true to build in background as
the default value is false.

• Parameter-Unique
Type:Boolean

Description-Creates an unique index so that collection will not accept insertion of document
where the index key or keys match existing value in the index.specify true to create unique index
as default value is false.

• Parameter-Name

Type:String

Description-The name of index if unspecified,MongoDb genreates an index name by


concatenating the name of indexed field and sort order.

• Parameter-Drop Dups

Type:Boolean

Description-creates a unique index on the field that may only have duplicates.MongoDB indexes
only the first occurence of a key and removes all document from the collection that contains
subsequent occurence of that key.specify true to craete unique index.The default value is false.

• Parameter-Sparse

Type:Boolean

Description-If true the index only refrences document with specified field.This indexes are less
sparse but behave diffrenty in same situation.

• Parameter-expire Aftersecond

Type:Integer

Description-Specifies a value, in seconds as a TTL to control how long MongoDb retains


document in collection.

• Parameter-V
Type:Index Version

Description-The Index Version number.The default index Version of mongodb running when
creating a index.

• Parameter-Weights

Type:Document

Description-The weight is a number ranging from 1 to 99,999 and denotes the significance of the
field relative to other indexed fields in terms of score.

• Parameter-default_language

Type:String

Description-For a text index, the language that determines the list of stop words and the rules for
stemmer and tokenizer.The default value is english.

• Parameter-Language_override

Type:String

Description-for a text index specify the name of field in the documents that contains the
language to override the default language.The default value is language

EXECUTION STEPS :

> use students switched to db students

> db.sinfo.insert({stud_name:'utkarsha',dept:'comp',addr:'chandigarh',class:'te'});

WriteResult({ "nInserted" : 1 })

> db.sinfo.insert({stud_name:'surabhi',dept:'it',addr:'mumbai',class:'fe'});

WriteResult({ "nInserted" : 1 })
> db.sinfo.insert({stud_name:'sanikaN',dept:'comp',addr:'pune',class:'se'});

WriteResult({ "nInserted" : 1 })

> db.sinfo.insert({stud_name:'sanikaM',dept:'mech',addr:'delhi',class:'be'});

WriteResult({ "nInserted" : 1 })

> db.sinfo.insert({stud_name:'sheenam',dept:'entc',addr:'mumbai',class:'fe'});

WriteResult({ "nInserted" : 1 })

> db.sinfo.insert({stud_name:'ridhima',dept:'it',addr:'pune',class:'se'});

WriteResult({ "nInserted" : 1 })

> db.sinfo.insert({stud_name:'rachna',dept:'mech',addr:'bangalore',class:'te'});

WriteResult({ "nInserted" : 1 })

> db.sinfo.find().pretty()

"_id" : ObjectId("540f0eb1e1cee50b9f1ee7bc"),

"stud_name" : "utkarsha",

"dept" : "comp",

"addr" : "chandigarh",

"class" : "te"

"_id" : ObjectId("540f0ee1e1cee50b9f1ee7bd"),

"stud_name" : "surabhi",

"dept" : "it",

"addr" : "mumbai",
"class" : "fe"

"_id" : ObjectId("540f0f0ce1cee50b9f1ee7be"),

"stud_name" : "sanikaN",

"dept" : "comp",

"addr" : "pune",

"class" : "se"

"_id" : ObjectId("540f0f26e1cee50b9f1ee7bf"),

"stud_name" : "sanikaM",

"dept" : "mech",

"addr" : "delhi",

"class" : "be"

"_id" : ObjectId("540f0f44e1cee50b9f1ee7c0"),

"stud_name" : "sheenam",

"dept" : "entc",

"addr" : "mumbai",

"class" : "fe"

}
{

"_id" : ObjectId("540f0fa1e1cee50b9f1ee7c1"),

"stud_name" : "ridhima",

"dept" : "it",

"addr" : "pune",

"class" : "se"

"_id" : ObjectId("540f0fd3e1cee50b9f1ee7c2"),

"stud_name" : "rachna",

"dept" : "mech",

"addr" : "bangalore",

"class" : "te"

> db.sinfo.update({stud_name:'utkarsha'},{"$set":{marks:'90'}})

WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

> db.sinfo.update({stud_name:'surabhi'},{"$set":{marks:'95'}})

WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

> db.sinfo.update({stud_name:'sanikaN'},{"$set":{marks:'80'}})

WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

> db.sinfo.update({stud_name:'sanikaM'},{"$set":{marks:'85'}})

WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

> db.sinfo.update({stud_name:'sheenam'},{"$set":{marks:'50'}})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

> db.sinfo.update({stud_name:'ridhima'},{"$set":{marks:'45'}})

WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

> db.sinfo.update({stud_name:'rachna'},{"$set":{marks:'75'}})

WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

> db.sinfo.find().pretty()

"_id" : ObjectId("540f0eb1e1cee50b9f1ee7bc"),

"stud_name" : "utkarsha",

"dept" : "comp",

"addr" : "chandigarh",

"class" : "te",

"marks" : "90"

"_id" : ObjectId("540f0ee1e1cee50b9f1ee7bd"),

"stud_name" : "surabhi",

"dept" : "it",

"addr" : "mumbai",

"class" : "fe",

"marks" : "95"

{"
_id" : ObjectId("540f0f0ce1cee50b9f1ee7be"),

"stud_name" : "sanikaN",

"dept" : "comp",

"addr" : "pune",

"class" : "se",

"marks" : "80"

"_id" : ObjectId("540f0f26e1cee50b9f1ee7bf"),

"stud_name" : "sanikaM",

"dept" : "mech",

"addr" : "delhi",

"class" : "be",

"marks" : "85"

"_id" : ObjectId("540f0f44e1cee50b9f1ee7c0"),

"stud_name" : "sheenam",

"dept" : "entc",

"addr" : "mumbai",

"class" : "fe",

"marks" : "50"

}
{

"_id" : ObjectId("540f0fa1e1cee50b9f1ee7c1"),

"stud_name" : "ridhima",

"dept" : "it",

"addr" : "pune",

"class" : "se",

"marks" : "45"

"_id" : ObjectId("540f0fd3e1cee50b9f1ee7c2"),

"stud_name" : "rachna",

"dept" : "mech",

"addr" : "bangalore",

"class" : "te",

"marks" : "75"

} ---------------------------------------------------------------------------------

1) > db.sinfo.find({stud_name:'sheenam'}).explain()

"cursor" : "BasicCursor",

"isMultiKey" : false,

"n" : 1,

"nscannedObjects" : 7,

"nscanned" : 7,
"nscannedObjectsAllPlans" : 7,

"nscannedAllPlans" : 7,

"scanAndOrder" : false,

"indexOnly" : false,

"nYields" : 0,

"nChunkSkips" : 0,

"millis" : 0,

"server" : "localhost.localdomain:27017",

"filterSet" : false

} ````````````````````````````````````````````````````````````````

2) > db.sinfo.ensureIndex({stud_name:1})

{ "createdCollectionAutomatically" : false,

"numIndexesBefore" : 1,

"numIndexesAfter" : 2,

"ok" : 1

} `````````````````````````````````````````````````````````````````

3) > db.sinfo.find({stud_name:'sheenam'}).explain()

"cursor" : "BtreeCursor stud_name_1",

"isMultiKey" : false,

"n" : 1,

"nscannedObjects" : 1,

"nscanned" : 1,
"nscannedObjectsAllPlans" : 1,

"nscannedAllPlans" : 1,

"scanAndOrder" : false,

"indexOnly" : false,

"nYields" : 0,

"nChunkSkips" : 0,

"millis" : 0,

"indexBounds" : { "stud_name" : [ [ "sheenam", "sheenam" ] ] },

"server" : "localhost.localdomain:27017",

"filterSet" : false

} > ````````````````````````````````````````````````````````````````````

4) > db.sinfo.ensureIndex({dept:1})

{ "createdCollectionAutomatically" : false,

"numIndexesBefore" : 2,

"numIndexesAfter" : 3,

"ok" : 1

} `````````````````````````````````````````````````````````````````````

5) > show collections;

sinfo system.indexes

> db.system.indexes.find()

{ "v" : 1, "key" : { "_id" : 1 },

"name" : "_id_", "ns" : "students.sinfo" }

{ "v" : 1,
"key" : { "stud_name" : 1 },

"name" : "stud_name_1",

"ns" : "students.sinfo" } { "v" : 1, "key" : { "dept" : 1 }, "name" : "dept_1", "ns" :


"students.sinfo" }

> ``````````````````````````````````````````````````````````````````````````

6) > db.sinfo.dropIndex({dept:1})

{ "nIndexesWas" : 3, "ok" : 1 } >

> db.system.indexes.find()

{ "v" : 1, "key" : { "_id" : 1 },

"name" : "_id_", "ns" : "students.sinfo" } { "v" : 1, "key" : { "stud_name" : 1 },

"name" : "stud_name_1", "ns" : "students.sinfo"

} > ``````````````````````````````````````````````````````````````````````````

7) > db.sinfo.find({},{stud_name:1,marks:1})

{ "_id" : ObjectId("540f0eb1e1cee50b9f1ee7bc"),

"stud_name" : "utkarsha",

"marks" : "90"

"_id" : ObjectId("540f0ee1e1cee50b9f1ee7bd"),

"stud_name" : "surabhi",

"marks" : "95"

{
"_id" : ObjectId("540f0f0ce1cee50b9f1ee7be"),

"stud_name" : "sanikaN",

"marks" : "80"

"_id" : ObjectId("540f0f26e1cee50b9f1ee7bf"),

"stud_name" : "sanikaM",

"marks" : "85"

"_id" : ObjectId("540f0f44e1cee50b9f1ee7c0"),

"stud_name" : "sheenam",

"marks" : "50"

"_id" : ObjectId("540f0fa1e1cee50b9f1ee7c1"),

"stud_name" : "ridhima",

"marks" : "45"

"_id" : ObjectId("540f0fd3e1cee50b9f1ee7c2"),

"stud_name" : "rachna",

"marks" : "75"
} > ``````````````````````````````````````````````````````````````````````````

8) > db.sinfo.find().sort({stud_name:1})

{ "_id" : ObjectId("540f0fd3e1cee50b9f1ee7c2"),

"stud_name" : "rachna",

"dept" : "mech",

"addr" : "bangalore",

"class" : "te",

"marks" : "75"

"_id" : ObjectId("540f0fa1e1cee50b9f1ee7c1"),

"stud_name" : "ridhima",

"dept" : "it",

"addr" : "pune",

"class" : "se",

"marks" : "45"

"_id" : ObjectId("540f0f26e1cee50b9f1ee7bf"),

"stud_name" : "sanikaM",

"dept" : "mech",

"addr" : "delhi",

"class" : "be",
"marks" : "85"

"_id" : ObjectId("540f0f0ce1cee50b9f1ee7be"),

"stud_name" : "sanikaN",

"dept" : "comp",

"addr" : "pune",

"class" : "se",

"marks" : "80"

"_id" : ObjectId("540f0f44e1cee50b9f1ee7c0"),

"stud_name" : "sheenam",

"dept" : "entc",

"addr" : "mumbai",

"class" : "fe",

"marks" : "50"

"_id" : ObjectId("540f0ee1e1cee50b9f1ee7bd"),

"stud_name" : "surabhi",

"dept" : "it",

"addr" : "mumbai",
"class" : "fe",

"marks" : "95"

"_id" : ObjectId("540f0eb1e1cee50b9f1ee7bc"),

"stud_name" : "utkarsha",

"dept" : "comp",

"addr" : "chandigarh",

"class" : "te",

"marks" : "90"

} `````````````````````````````````````````````````````````````````````````

9) > db.sinfo.find().sort({class:1,stud_name:1})

{ "_id" : ObjectId("540f0f26e1cee50b9f1ee7bf"),

"stud_name" : "sanikaM",

"dept" : "mech",

"addr" : "delhi",

"class" : "be",

"marks" : "85"

"_id" : ObjectId("540f0f44e1cee50b9f1ee7c0"),

"stud_name" : "sheenam",

"dept" : "entc",
"addr" : "mumbai",

"class" : "fe",

"marks" : "50"

"_id" : ObjectId("540f0ee1e1cee50b9f1ee7bd"),

"stud_name" : "surabhi",

"dept" : "it",

"addr" : "mumbai",

"class" : "fe",

"marks" : "95"

"_id" : ObjectId("540f0fa1e1cee50b9f1ee7c1"),

"stud_name" : "ridhima",

"dept" : "it",

"addr" : "pune",

"class" : "se",

"marks" : "45"

"_id" : ObjectId("540f0f0ce1cee50b9f1ee7be"),

"stud_name" : "sanikaN",
"dept" : "comp",

"addr" : "pune",

"class" : "se",

"marks" : "80"

"_id" : ObjectId("540f0fd3e1cee50b9f1ee7c2"),

"stud_name" : "rachna",

"dept" : "mech",

"addr" : "bangalore",

"class" : "te",

"marks" : "75"

"_id" : ObjectId("540f0eb1e1cee50b9f1ee7bc"),

"stud_name" : "utkarsha",

"dept" : "comp",

"addr" : "chandigarh",

"class" : "te",

"marks" : "90"

} > ``````````````````````````````````````````````````````````````````````````````

10) > db.sinfo.find({'marks':{"$gte":'40',"$lte":'60'}}).pretty()

{ "_id" : ObjectId("540f0f44e1cee50b9f1ee7c0"),
"stud_name" : "sheenam",

"dept" : "entc",

"addr" : "mumbai",

"class" : "fe",

"marks" : "50"

"_id" : ObjectId("540f0fa1e1cee50b9f1ee7c1"),

"stud_name" : "ridhima",

"dept" : "it",

"addr" : "pune",

"class" : "se",

"marks" : "45"

} > ````````````````````````````````````````````````````````````

11) > db.sinfo.insert({stud_name:'bhargavi',dept:'comp',addr:'mumbai',class:'fe',marks:'70'})

WriteResult({ "nInserted" : 1 })

> db.sinfo.find({addr:'mumbai',class:'fe',dept:'comp'}).pretty()

"_id" : ObjectId("54101208b5f4773d09ee91af"),

"stud_name" : "bhargavi",

"dept" : "comp",

"addr" : "mumbai",

"class" : "fe",
"marks" : "70"

} > ```````````````````````````````````````````````````````````````````

CONCLUSION : Students successfully implemeted indexing and aggregation in mongo DB.


GROUP B

EXPERIMENT 12

OBJECTIVE : To study and implement Map reduces operation with suitable example using
MongoDB.

PROBLEM STATEMENT: Implement Map reduces operation with suitable example using
MongoDB.

HARDWARE REQUIREMENT :

2 GHz dual core processor.


2 GiB RAM (system memory)
25 GB of hard-drive space (or USB stick, memory card or external drive but see LiveCD for an
alternative approach)

SOFTWARE REQUIREMENT :
Operating System- Ubuntu 16.04
Database- Mongo DB
OUTCOME : After completion of assignment student are able to implement Map reduces
operation with suitable example using MongoDB.
THEORY :
Map-reduce :-

As per the Mongodb documentation. Map reduce is data processing paradigm for condensing
large volume of data into useful aggregated result Mongodb user Map-reduce is command for
map-reduce option. Map-reduce in generally used for processing large data sets.

Map-Reduce command:-

following are the syntax of the basic map-reduce command

db.collection.mapreduce{

function(){exit(key , value);} // Map function.

function(key,values){return reduce function};

out:collection;
qyery:document;

sort:document;

limit:number;

the map-reduce function first queries the collection then map the result document to emit key-
value pair which is then reduced based on the keys that have multiple value.in above syntax

• map-reduce in javascript function , that maps a value with a key & limit a key value pair

• reduce is a javascript function that reduces or graphs all the document having same key.

• out specifics the location of the map-reduce query result.

• query specifies the optional selection criteria for selecting document .

• sort specifies the optional sort criteria.

USE Map-Reduce :-

Consider the following document structure sorting user postd the document stores user_name of
the user & status of post

”post_txt”:”tutorialsponit is an awsome

website for tutorials”.

”user_name”:”mark”;

“status”:”active”;

new we will use mapreduce function on our post collection to select all the active post group
them an the basis of user_name & then count the number of post by each user using following
code

db.collection.mapreduce{
function(){exit(this user_id);}

function(key,values){return array.sun(values)};

query :{status :”active”},

out :”post_total”;

the above map-reduce query output the following result

{”result”:”post_total”,

”time millis”:9,

”count”:{

”input”:4;

”emit”:4;

”reduce”:2;

”output”:2;

”ok” :1

the result shown that total of4 documents method

The query map function emitted 4 documents with key value pair & finally reduce function
group mapped document having same key into2.

STEPS:

• open the terminal for staring of mongodb server

write on terminal1:
1. cd mongodb-linux-x86-64-2.6.1

2. cd bin

3. ./mongod --dbpath /home/bvcoew/BVCOEWdata

• open another terminal for staring of mongodb client

write on terminal 2:

1. cd mongodb-linux-x86-64-2.6.1

2. cd bin

3. ./mongo

• perform mapreduce queries.

EXECUTION STEPS:
> use bank

switched to db bank

> db.cust.insert({cust_id:1,amt:1000})

WriteResult({ "nInserted" : 1 })

> db.cust.insert({cust_id:2,amt:4000})

WriteResult({ "nInserted" : 1 })

> db.cust.insert({cust_id:3,amt:4000})

WriteResult({ "nInserted" : 1 })

> db.cust.insert({cust_id:4,amt:8000})

WriteResult({ "nInserted" : 1 })

> db.cust.insert({cust_id:2,amt:2000})

WriteResult({ "nInserted" : 1 })

> db.cust.insert({cust_id:6,amt:6000})
WriteResult({ "nInserted" : 1 })

> var mapfn=function(){emit(this.cust_id,this.amt)};

> var redfn=function(key,values){return Array.sum(values);};

> db.cust.mapReduce(mapfn,redfn,{'out':'result'})

{ "result" : "result", "timeMillis" : 61, "counts" : { "input" : 6, "emit" : 6, "reduce" : 1, "output" :


5 }, "ok" : 1, }

> db.result.find() { "_id" : 1, "value" : 1000 }

{ "_id" : 2, "value" : 6000 } { "_id" : 3, "value" : 4000 } { "_id" : 4, "value" : 8000 } { "_id" : 6,
"value" : 6000 }

> ``````````````````````````````````````````````````````````````

> use custom

switched to db custom

> db.order.insert({cust_id:1,item:'keyboard',quantity:20})

WriteResult({ "nInserted" : 1 })

> db.order.insert({cust_id:2,item:'cpu',quantity:10})

WriteResult({ "nInserted" : 1 })

> db.order.insert({cust_id:3,item:'monitor',quantity:50})

WriteResult({ "nInserted" : 1 })

> db.order.insert({cust_id:4,item:'keyboard',quantity:50})

WriteResult({ "nInserted" : 1 })

> db.order.insert({cust_id:5,item:'cpu',quantity:60})

WriteResult({ "nInserted" : 1 })

> db.order.insert({cust_id:6,item:'keyboard',quantity:70})

WriteResult({ "nInserted" : 1 })
> var mapfunction=function(){emit(this.item,this.quantity)};

> var reducefunction=function(key,values){return Array.sum(values);};

> db.order.mapReduce(mapfunction,reducefunction,{'out':'result'})

{ "result" : "result", "timeMillis" : 87, "counts" : { "input" : 6, "emit" : 6, "reduce" : 2, "output" :


3 }, "ok" : 1, }

> db.result.find() { "_id" : "cpu", "value" : 70 }

{ "_id" : "keyboard", "value" : 140 } { "_id" : "monitor", "value" : 50 }

CONCLUSION: Students successfully implemented Map reduces operation using MongoDB.


GROUP C

EXPERIMENT 13

OBJECTIVE : To study and implement MYSQL database connectivity with Java Implement
Database navigation operations (add, delete, edit,) using JDBC.

PROBLEM STATEMENT: Implement MYSQL/Oracle database connectivity with PHP/


python/Java Implement Database navigation operations (add, delete, edit,) using ODBC/JDBC.

HARDWARE REQUIREMENT :

2 GHz dual core processor.


2 GiB RAM (system memory)
25 GB of hard-drive space (or USB stick, memory card or external drive but see LiveCD for an
alternative approach)

SOFTWARE REQUIREMENT :
Operating System- Ubuntu 16.04
Database- Mysql
IDE : Eclipse

OUTCOME : After completing assignment student are able to implement MYSQL database
connectivity with JSP and database navigation operations (add, delete, edit,) using JDBC.

THEORY :

JDBC

(i) JDBC is used for accessing databases from Java applications.

(ii)Information is transferred from relations to objects and vice-versa:

-databases optimized for searching/indexing

-objects optimized for engineering/flexibility

JDBC ARCHITECTURE:
EXECUTION STEPS :
//package mg;

import java.io.*;
import java.sql.DriverManager;

import java.sql.Connection;

import java.sql.SQLException;

import java.sql.PreparedStatement;

import java.sql.ResultSet;

import java.sql.Statement;

public class Conn

private static PreparedStatement preparedStatement = null;

private static ResultSet rs = null;

static int id,temp,ans,ch,sal;

static String name,dept,job; // JDBC driver name and database URL

static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";

static final String DB_URL = "jdbc:mysql://172.24.3.36:3306/maindb"; // Database credentials

static final String USER = "student"; //you can assign your user name who havin remote login
permissions

static final String PASS = "student";

public static void main(String[] args)

Connection conn = null;

Statement stmt = null;

try

{
//STEP 2: Register JDBC driver Class.forName("com.mysql.jdbc.Driver");

//STEP 3: Open a connection System.out.println("Connecting to a selected database...");

conn = DriverManager.getConnection(DB_URL, USER, PASS);

System.out.println("Connected database successfully...");

System.out.println("You made it, take control your database now!");

do

System.out.println("1:Create Table " );

System.out.println("2: Insert in table " );

System.out.println("3: Display Table ");

System.out.println("4:Delete from table");

System.out.println("5:Update table");

System.out.println("6: Display first and last " );

System.out.println("7: Display particular record ");

System.out.println("8: Join between employee data and department job ");

System.out.println("9:Close database");

BufferedReader bufr=new BufferedReader(new InputStreamReader(System.in));

System.out.println("Ente choice :");

ch=Integer.parseInt(bufr.readLine());

switch(ch)

case 1:

//Execute a query to create table System.out.println("Creating table in given database...");


stmt = conn.createStatement();

String sql = "CREATE TABLE employee " + "(id INTEGER primary key, " + "name
varchar(15),"+ " dept VARCHAR(255),"+ "sal int);";

stmt.executeUpdate(sql);

System.out.println("Created table in given database...");

break;

case 2: preparedStatement = conn.prepareStatement("insert into maindb.employee values


(?, ?, ?, ?)");

// preparedStatements can use variables and are more efficient // "name, class from
jdbc.student");

// parameters start with 1

System.out.println("Ente emp id :");

id=Integer.parseInt(bufr.readLine());

System.out.println("Ente emp name :");

name=bufr.readLine();

System.out.println("Ente dept :");

dept=bufr.readLine();

System.out.println("Ente salary :");

sal=Integer.parseInt(bufr.readLine());

preparedStatement.setInt(1, id);

preparedStatement.setString(2,name);

preparedStatement.setString(3, dept);

preparedStatement.setInt(4, sal);

preparedStatement.executeUpdate();

break;
case 3:

System.out.println("Creating statement...");

stmt = conn.createStatement( ResultSet.TYPE_SCROLL_INSENSITIVE,


ResultSet.CONCUR_READ_ONLY);

String sql1;

sql1 = "SELECT id, name, dept,sal FROM employee";

rs = stmt.executeQuery(sql1);

//Display all values

while (rs.next())

// it is possible to get the columns via name

// also possible to get the columns via the column number

// which starts at 1

// e.g., resultSet.getSTring(2);

id = rs.getInt("id");

name = rs.getString("name");

dept = rs.getString("dept");

sal = rs.getInt("sal");

System.out.println("Id: " + id);

System.out.println("Name: " + name);

System.out.println("Class: " + dept);

System.out.println("Marks: " + sal);

}
break;

case 4:

preparedStatement = conn.prepareStatement("Delete from employee WHERE id =?");

System.out.println("Ente emp id you want to delete :");

id=Integer.parseInt(bufr.readLine());

preparedStatement.setInt(1, id);

preparedStatement.executeUpdate();

break;

case 5:

preparedStatement = conn.prepareStatement("UPDATE employee SET sal = ? WHERE id =?");

System.out.println("Ente emp id you want to update :");

id=Integer.parseInt(bufr.readLine());

System.out.println("Ente new salary :");

sal=Integer.parseInt(bufr.readLine());

preparedStatement.setInt(2, id);

preparedStatement.setInt(1, sal);

preparedStatement.executeUpdate();

break;

case 6:

System.out.println("Creating statement...");

stmt = conn.createStatement( ResultSet.TYPE_SCROLL_INSENSITIVE,


ResultSet.CONCUR_READ_ONLY);

sql1 = "SELECT id, name, dept,sal FROM employee";

rs = stmt.executeQuery(sql1); // Move cursor to the last row.


System.out.println("Moving cursor to the last...");

rs.last();

//STEP 5: Extract data from result set

System.out.println("Displaying record..."); //Retrieve by column name id = rs.getInt("id");

name = rs.getString("name");

dept = rs.getString("dept");

sal = rs.getInt("sal");

//Display values

System.out.print("ID: " + id);

System.out.print(", Name: " + name);

System.out.print(", dept: " + dept);

System.out.println(", Salary: " + sal);

// Move cursor to the first row.

System.out.println("Moving cursor to the first row...");

rs.first();

//Extract data from result set System.out.println("Displaying record..."); //Retrieve by column


name id = rs.getInt("id");

name = rs.getString("name");

dept = rs.getString("dept");

sal = rs.getInt("sal");

//Display values

System.out.print("ID: " + id);

System.out.print(", Name: " + name);


System.out.print(", dept: " + dept);

System.out.println(", salary: " + sal);

case 7:

System.out.println("Creating statement...");

stmt = conn.createStatement( ResultSet.TYPE_SCROLL_INSENSITIVE,


ResultSet.CONCUR_READ_ONLY);

sql1 = "SELECT id, name, dept,sal FROM employee";

rs = stmt.executeQuery(sql1); // Move cursor to the first row.

System.out.println("Moving cursor to the first row...");

rs.first();

System.out.println("Enter id you want to print details: :");

temp=Integer.parseInt(bufr.readLine());

while (rs.next())

// it is possible to get the columns via name

// also possible to get the columns via the column number

// which starts at 1

// e.g., resultSet.getString(2);

if(rs.getInt("id")==temp)

id = rs.getInt("id");

name = rs.getString("name");

dept = rs.getString("dept");

sal = rs.getInt("sal");
System.out.println("Id: " + id);

System.out.println("Name: " + name);

System.out.println("Class: " + dept);

System.out.println("Marks: " + sal);

break;

case 8:

System.out.println("Creating statement...");

stmt = conn.createStatement( ResultSet.TYPE_SCROLL_INSENSITIVE,


ResultSet.CONCUR_READ_ONLY);

sql1 = "SELECT * FROM employee inner join department where employee.id=department.id";

rs = stmt.executeQuery(sql1); // Move cursor to the first row.

System.out.println("Moving cursor to the first row...");

rs.first();

System.out.println("Enter id you want to print details: :");

temp=Integer.parseInt(bufr.readLine());

while (rs.next())

// it is possible to get the columns via name

// also possible to get the columns via the column number

// which starts at 1

// e.g., resultSet.getString(2);
if(rs.getInt("id")==temp)

id = rs.getInt("id");

name = rs.getString("name");

dept = rs.getString("dept");

job = rs.getString("job");

System.out.println("Id: " + id);

System.out.println("Name: " + name);

System.out.println("dept: " + dept);

System.out.println(" Job :" + job);

break;

case 9:

//Clean-up environment

rs.close();

stmt.close();

conn.close();

break;

System.out.println("Do you wnat to continue [no-0/yes-1] :");

ans=Integer.parseInt(bufr.readLine());

}while(ans==1);
} catch(Exception e)

//Handle errors for Class.forName

//[can figure out which class, method and line caused the exception]

e.printStackTrace();

System.out.println("Goodbye!"); }//end main

}//end JDBCExample

OUTPUT:

Connecting to a selected database...

Connected database successfully...

You made it, take control your database now!

1:Create Table

2: Insert in table

3: Display Table

4:Delete from table

5:Update table

6: Display first and last

7: Display particular record

8: Join between employee data and department job

9:Close database

Ente choice : 2

Ente emp id : 5
Ente emp name : bnm

Ente dept : mech

Ente salary : 50000

Do you wnat to continue [no-0/yes-1] : 1

1:Create Table

2: Insert in table

3: Display Table

4:Delete from table

5:Update table

6: Display first and last

7: Display particular record

8: Join between employee data and department job

9:Close database

Ente choice : 3

Creating statement...

Id: 1

Name: abc

Class: comp

Marks: 20000

Id: 2

Name: xyz

Class: entc

Marks: 30000
Id: 5

Name: bnm

Class: mech

Marks: 50000

Do you wnat to continue [no-0/yes-1] : 1

1:Create Table

2: Insert in table

3: Display Table

4:Delete from table

5:Update table

6: Display first and last

7: Display particular record

8: Join between employee data and department job

9:Close database

Ente choice : 5

Ente emp id you want to update : 1

Ente new salary : 35000

Do you wnat to continue [no-0/yes-1] : 1

1:Create Table

2: Insert in table

3: Display Table

4:Delete from table

5:Update table
6: Display first and last

7: Display particular record

8: Join between employee data and department job

9:Close database

Ente choice : 3

Creating statement...

Id: 1

Name: abc

Class: comp

Marks: 35000

Id: 2

Name: xyz

Class: entc

Marks: 30000

Id: 5

Name: bnm

Class: mech

Marks: 50000

Do you wnat to continue [no-0/yes-1] : 1

1:Create Table

2: Insert in table

3: Display Table

4:Delete from table


5:Update table

6: Display first and last

7: Display particular record

8: Join between employee data and department job

9:Close database

Ente choice : 6

Creating statement...

Moving cursor to the last...

Displaying record...

ID: 5,

Name: bnm,

dept: mech,

Salary: 50000

Moving cursor to the first row...

Displaying record...

ID: 1,

Name: abc,

dept: comp,

salary: 35000

Creating statement...

Moving cursor to the first row...

Enter id you want to print details: : 2

Id: 2
Name: xyz

Class: entc

Marks: 30000

Do you wnat to continue [no-0/yes-1] : 1

1:Create Table

2: Insert in table

3: Display Table

4:Delete from table

5:Update table

6: Display first and last

7: Display particular record

8: Join between employee data and department job

9:Close database

Ente choice : 7

Creating statement...

Moving cursor to the first row...

Enter id you want to print details: : 5

Id: 5

Name: bnm

Class: mech

Marks: 50000

Do you wnat to continue [no-0/yes-1] : 1

1:Create Table
2: Insert in table

3: Display Table

4:Delete from table

5:Update table

6: Display first and last

7: Display particular record

8: Join between employee data and department job

9:Close database

Ente choice : 8

Creating statement...

Moving cursor to the first row...

Enter id you want to print details: : 1

Id: 1

Name: abc

dept: comp

Job :prg

Do you wnat to continue [no-0/yes-1] : 1

1:Create Table

2: Insert in table

3: Display Table

4:Delete from table

5:Update table

6: Display first and last


7: Display particular record

8: Join between employee data and department job

9:Close database

Ente choice : 9

Do you wnat to continue [no-0/yes-1] : 0

Goodbye!

CONCLUSION :

Students successfully implemented JSP Mysql connectivity.

You might also like