0% found this document useful (0 votes)
4 views133 pages

Final Dbms Lab Manual

The document is a laboratory manual for a Database Management System course, detailing various SQL commands and their implementations, including Data Definition Language (DDL), Data Manipulation Language (DML), and Transaction Control Language (TCL). It covers creating databases and tables, manipulating data, and using subqueries and nested queries. Additionally, it includes sample queries and exercises for practical understanding of database operations.

Uploaded by

sumathi.b
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)
4 views133 pages

Final Dbms Lab Manual

The document is a laboratory manual for a Database Management System course, detailing various SQL commands and their implementations, including Data Definition Language (DDL), Data Manipulation Language (DML), and Transaction Control Language (TCL). It covers creating databases and tables, manipulating data, and using subqueries and nested queries. Additionally, it includes sample queries and exercises for practical understanding of database operations.

Uploaded by

sumathi.b
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/ 133

VEL TECH HIGH TECH

Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE


An Autonomous Institution

21HC39P

DATABASE MANAGEMENT SYSTEM


LABORATORY

LAB MANUAL

Prepared by,
B.Sumathi & V.Tamilsevi
Assistant Professor/IT
1. Data Definition Commands, Data Manipulation Commands for

inserting, deleting, updating andretrieving Tables and Transaction


Control statements
2. Database Querying – Simple queries, Nested queries, Sub queries and

Joins.
3. Creating an employee database to set various constraints and

Creation of Views Indexes, Savepoint.


4. Database Programming: Implicit and Explicit Cursors

5. Write a PL/SQL block that handles all types of exceptions.

6. To create PL/SQL functions and to implement the stored

procedures in SQL (Procedures andFunctions).


7. To study the basics of front-end tools.

8. Creation of Database Triggers

9. Database Design using ER modeling, normalization and Implementation

for any application


10. Creation of Database in MS Access.

11. Database connectivity using Front End Tools (Application Development

using Oracle/ Mysql)


12. Case study of Big Data and NoSQL.
EX.NO:1(i) IMPLEMENTATION OF DDL COMMANDS
Date:

AIM:
To create table and execute data definition commands.

SQL: create command

Create is a DDL SQL command used to create a table or a database in relational database management
system.

Creating a Database
To create a database in RDBMS, create command is used.

Syntax
CREATE DATABASE <DB_NAME>;

Example for creating Database

CREATE DATABASE Test;

The above command will create a database named Test, which will be an empty schema without any
table.

To create tables in this newly created database, we can again use the create command.

Creating a Table
Create command can also be used to create tables. Now when we create a table, we have to specify the
details of the columns of the tables too. We can specify the names and data types of various columns in the create
command itself.

Syntax

CREATE TABLE <TABLE_NAME> (


Column_name1 datatype1, column_name2 datatype2, column_name3 datatype3,
column_name4 datatype4
);
SQL: ALTER command
Alter command is used for altering the table structure, such as,
 To add a column to existing table
 To rename any existing column

 To change data type of any column or to modify its size.


 To drop a column from the table.
ALTER Command: Add a new Column
Using ALTER command we can add a column to any existing table.

Syntax:
ALTER TABLE table_name ADD (column_name datatype);

ALTER Command: Add multiple new Columns


Using ALTER command we can even add multiple new columns to any existing table.

Syntax
ALTER TABLE table_name ADD( column_name1 datatype1, column-name2 datatype2,.. );

ALTER Command: Add Column with default value


ALTER command can add a new column to an existing table with a default value too. The default value is
used when no value is inserted in the column.

Syntax

ALTER TABLE table_name ADD column( column-name1 datatype1 DEFAULT some_value);

ALTER Command: Modify an existing Column


ALTER command can also be used to modify data type of any existing column.

Syntax

ALTER TABLE table_name modify column (column_name datatype);

ALTER Command: Rename a Column


Using ALTER command you can rename an existing column.

Syntax

ALTER TABLE table_name RENAME old_column_name TO new_column_name;

ALTER Command: Drop a Column


ALTER command can also be used to drop or remove columns.

Syntax
ALTER TABLE table_name DROP column (column_name datatype);

TRUNCATE command
TRUNCATE command removes all the records from a table. But this command will not destroy the
table's structure. When we use TRUNCATE command on a table its (auto-increment) primary key is also
initialized.

Syntax

TRUNCATE TABLE table_name

DROP command
DROP command completely removes a table from the database. This command will also destroy the table
structure and the data stored in it.

Syntax

DROP TABLE table_name

RENAME query
RENAME command is used to set a new name for any existing table.

Syntax

RENAME TABLE old_table_name to new_table_name


SAMPLE QUERIES

Mysql>Create table passenger3(passportId Integer Primary Key,Name varchar(10) Not


Null,Age Integer Not Null,Sex char,Address varchar(20) Not Null);

Mysql> desc passenger3;

USING ALTER COMMAND

Adding Extra column to Existing Table

Mysql>Alter table passenger3 add column TicketNo varchar(10);


Mysql>Alter Table passenger3 add Foreign key(TicketNo) references Ticket(TicketNo);

Mysql>Alter Table passenger3 Modify column Name varchar(20);


Mysql>Alter table passenger drop foreign key fk1;

Mysql> Alter table passenger2 Drop column TicketNo;

DROP TABLE

mysql> drop table passenger2;


Query OK, 0 rows affected (0.09 sec)
TRUNCATE TABLE

mysql> create table student1(studid integer,sname varchar(10));


Query OK, 0 rows affected (0.11 sec)
mysql> truncate table student1;
Query OK, 0 rows affected (0.06 sec)

QUERIES

Q1. Create a table called EMP with the following structure.

Name Type
---------- ----------------------
EMPNO INTEGER(6)
ENAME VARCHAR(20)
JOB VARCHAR(10)
DEPTNO INTEGER(3)
SAL INTEGER(7)
Allow NULL for all columns except ename and job.

Solution:
1. Understand create table syntax.
2. Use the create table syntax to create the said tables.

mysql> CREATE TABLE EMP(EMPNO INTEGER(6),ENAME VARCHAR(20),JOB VARCHAR(10),DEPTNO


INTEGER(3),SAL INTEGER(7));
Query OK, 0 rows affected (0.14 sec)

Q2: Add a column experience to the emp table.


experience numeric null allowed.

Solution:
1. Learn alter table syntax.
2. Define the new column and its data type.
3. Use the alter table syntax.
mysql> alter table emp add column(experience integer(2));
Query OK, 0 rows affected (0.23 sec)

Q3: Modify the column width of the job field of emp table.

Solution:
1. Use the alter table syntax.
2. Modify the column width and its data type.

mysql> alter table emp modify column job varchar(12);


Query OK, 0 rows affected (0.25 sec)

Q4: Create dept table with the following structure.

Name Type
------------ ---------------------
DEPTNO INTEGER(2)
DNAME VARCHAR(10)
LOC VARCHAR(10)
Deptno as the primarykey

Solution:
1. Understand create table syntax.
2. Decide the name of the table.
3. Decide the name of each column and its data type.
4. Use the create table syntax to create the said tables.
5. Create primary key constraint for each table as understand from logical table structure.

mysql> create table dept(deptno integer(2) primary key,dname varchar(10),loc varchar(10));


Query OK, 0 rows affected (6.65 sec)
Q5: Drop a column experience to the emp table.
Solution:
1. Use the alter table syntax to drop the column.

mysql> alter table emp drop column experience;


Query OK, 0 rows affected (0.33 sec)

Q6: Truncate the emp table and drop the dept table

Solution:
1. Use the drop, truncate table syntax to drop and truncate the table.

mysql> truncate table emp;


Query OK, 0 rows affected (0.14 sec)

mysql> drop table dept;


Query OK, 0 rows affected (0.09 sec)
EX.NO:1(ii) IMPLEMENTATION OF DML COMMANDS

Date:

AIM:

To study the various DML commands and implement them on the database.

DML COMMANDS

DML commands are the most frequently used SQL commands and is used to query and manipulate the
existing database objects. Some of the commands are Insert, Select, Update, Delete.

INSERT :
Insert command is used to insert data into a table.
Syntax:
INSERT INTO table_name VALUES(data1, data2, ...)

SELECT:
It is used to retrieve information from the table.
Syntax:
Select * from Tablename;

Select using WHERE Clause:


It is used to retrieve information from the table based on condition.
Syntax:
Select * from Tablename Where <Condition>;
Select A1, A2, …, An from Tablename Where <Condition>;

UPDATE :
UPDATE command is used to update any record of data in a table.
Syntax
UPDATE table_name SET column_name = new_value WHERE some_condition;
DELETE :
DELETE command is used to delete data from a table.
Syntax:
DELETE FROM table_name;
Delete from table-name Where <Condition>;

SAMPLE QUERIES:
INSERT COMMAND ON BUS2 & PASSENGER2 RELATIONS
mysql> select * from Bus2;

Empty set (0.00 sec)

mysql> insert into Bus2 values(1234,'Hyderabad','Tirupathi');Query

OK, 1 row affected (0.03 sec)

mysql> insert into Bus2 values(2345,'Hyderabad','Banglore');Query

OK, 1 row affected (0.01 sec)

mysql> insert into Bus2 values(23,'Hyderabad','Kolkata');Query OK,

1 row affected (0.03 sec)

mysql> insert into Bus2 values(45,'Tirupathi','Banglore');Query OK,

1 row affected (0.03 sec)

mysql> insert into Bus2 values(34,'Hyderabad','Chennai');Query OK,

1 row affected (0.03 sec)


mysql> select * from Bus2;
mysql> select * from Passenger2;

Empty set (0.00 sec)

mysql> insert into Passenger2 values(145,'Ramesh',45,'M','abc123');Query

OK, 1 row affected (0.05 sec)

mysql> insert into Passenger2 values(278,'Geetha',36,'F','abc124');Query

OK, 1 row affected (0.02 sec)

mysql> insert into Passenger2 values(4590,'Ram',30,'M','abc12');

Query OK, 1 row affected (0.03 sec)

mysql> insert into Passenger2 values(6789,'Ravi',50,'M','abc14');

Query OK, 1 row affected (0.03 sec)

mysql> insert into Passenger2 values(5622,'Seetha',32,'F','abc55');Query

OK, 1 row affected (0.03 sec)

mysql> select * from Passenger2;


UPDATE COMMAND ON BUS2 RELATION

UPDATE Selected Rows & Multiple Rows

mysql> Update Bus2 SET Source='Secundrabad' where BusNo=1234;

Query OK, 1 row affected (0.05 sec)

Rows matched: 1 Changed: 1 Warnings: 0


DELETE COMMAND ON BUS2 RELATION

DELETES Selected Rows and Multiple Rows

mysql> Delete from Bus2 where BusNo=1234;

Query OK, 1 row affected (0.05 sec)

mysql> select * from Bus2;


mysql> Delete from Bus2 where Source=’Secundrabad’; Query OK, 1 row affected (0.05 sec)mysql>

select * from Bus2;


Q1: Insert a single record into dept table.

Solution:
mysql> insert into dept values (1,'IT','Tholudur');
Query OK, 1 row affected (0.05 sec)

Q2: Update the emp table to set the salary of all employees to Rs15000/- who are working as ASP.

Solution:

Mysql>select* from emp;

EMPNO ENAME JOB DEPTNO SAL

1 Mathi AP 1 10000
2 Arjun ASP 2 12000
3 Gugan ASP 1 12000

SQL> update emp set sal=15000 where job='ASP'; 2 rows updated.


SQL> select * from emp;

EMPNO ENAME JOB DEPTNO SAL

1 Mathi AP 1 10000
2 Arjun ASP 2 15000
3 Gugan ASP 1 15000

Q3: Create a pseudo table employee with the same structure as the table emp and insert rows into the
table using select clauses.

Solution:
Q4: select employee name, job from the emp table.

Solution:

Q5: Delete only those who are working as lecturer.

Solution:
Q6: List the records in the emp table orderby salary in descending order.

Solution:

Q7:List the records in the emp table orderby salary in ascending order.

Solution:
EX.NO:1(iii) IMPLEMENTATION OF TCL COMMANDS

Date:

AIM:

To study the various TCL commands and implement them on the database.

TCL COMMANDS

Transaction Control Language (TCL) commands are used to manage transactions in the database. These are
used to manage the changes made to the data in a table by DML statements. It also allows statements to be grouped
together into logical transactions.

COMMIT command
COMMIT command is used to permanently save any transaction into the database. To avoid that, we use
the COMMIT command to mark the changes as permanent.

SYNTAX
COMMIT;

ROLLBACK command
This command restores the database to last commited state. It is also used with SAVEPOINT command to
jump to a savepoint in an ongoing transaction.

SYNTAX
ROLLBACK TO savepoint_name;

SAVEPOINT command
SAVEPOINT command is used to temporarily save a transaction so that you can rollback to that point
whenever required.

SYNTAX
SAVEPOINT savepoint_name;
QUERIES

Consider the following tables namely “DEPT” and “EMP”


Their schemas are as follows :
Dept( deptno , dname , loc);
Emp (empno,ename,job,deptno,sal );

Q1: Write a query to implement the save point.

Solution:

Q2: Write a query to implement the rollback.


Solution:

Q3: Write a query to implement the commit.

Solution:
EX.NO:2(i) IMPLEMENTATION OF SUB QUERIES AND NESTED QUERIES

Date:

AIM:

To study the various Sub Queries and Nested Queries in MYSQL and implement them on the database.

SUBQUERY & NESTED QUERY

A subquery in MySQL is a query, which is nested into another SQL query and embedded with SELECT,
INSERT, UPDATE or DELETE statement along with the various operators. We can also nest the subquery
with another subquery. A subquery is known as the inner query, and the query that contains subquery is known
as the outer query. The inner query executed first gives the result to the outer query, and then the main/outer
query will be performed. MySQL allows us to use subquery anywhere, but it must be closed within parenthesis.
All subquery forms and operations supported by the SQL standard will be supported in MySQL also.

When a query is included inside another query, the Outer query is known as Main Query, and Inner query is
known as Subquery. In Nested Query, Inner query runs first, and only once. Outer query is executed with result
from Inner query.

Subquery Syntax

SELECT column_list (s) FROM table_name

WHERE column_name OPERATOR

(SELECT column_list (s) FROM table_name [WHERE])


SAMPLE QUERIES

Q1:Simple MYSQL statement that returns the employee detail whose id matches in a subquery:

COMPARISON OPERATOR

Q2:Simple MYSQL statement that returns the employee detail whose income is more than 350000 with the
help of subquery.
Q3: To find employee details with maximum income using a subquery.

IN or NOT-IN Operator

Table: Student

Table: Student2

Q3:To find the student detail who does not belong to Los Angeles City from both tables.
FROM CLAUSE

Q4:To find the maximum, minimum, and average number of items in the order table.

CORRELATED SUBQUERY

Q5:To select an employee name and city whose income is higher than the average income of all employees in
each city.
EXISTS OR NOT EXISTS

Q6: EXISTS operator to find the name, occupation, and age of the customer who has placed at least one
order.
Q7.NOT EXISTS operator that returns the customer details who have not placed an order.
EXAMPLES OF Subqueries with ALL , ANY.

Querying (using ANY, ALL, IN, Exists, NOT EXISTS, UNION, INTERSECT, Constraints etc.)
Practice the following Queries:

1. Display unique PNR_NO of all passengers


2. Display all the names of male passengers.
3. Display the ticket numbers and names of all the passengers.
4. Find the ticket numbers of the passengers whose name start with ‘r’ and ends with ‘h’.
5. Find the names of Passengers whose age is between 30 and 45.
6. Display all the passengers names beginning with ‘A’.
7. Display the sorted list of Passengers names
mysql> insert into passenger2 values(82302,'Smith',23,'M','Hyderabad');Query OK,

1 row affected (0.02 sec)

mysql> insert into passenger2 values(82303,'Neha',23,'F','Hyderabad');Query

OK, 1 row affected (0.01 sec)

mysql> insert into passenger2 values(82304,'Neha',35,'F','Hyderabad');Query

OK, 1 row affected (0.03 sec)

mysql> insert into passenger2 values(82306,'Ramu',40,'M','Hyderabad');Query OK,

1 row affected (0.02 sec)

mysql> insert into passenger2 values(82308,'Aakash',40,'M','Hyderabad');Query

OK, 1 row affected (0.02 sec)

mysql> insert into passenger2 values(82402,'Aravind',42,'M','Hyderabad');Query

OK, 1 row affected (0.02 sec)

mysql> insert into passenger2 values(82403,'Avinash',42,'M','Hyderabad');Query

OK, 1 row affected (0.02 sec)

mysql> insert into passenger2 values(82502,'Ramesh',23,'M','Hyderabad');Query

OK, 1 row affected (0.02 sec)

mysql> insert into passenger2 values(82602,'Rajesh',23,'M','Hyderabad');Query OK,

1 row affected (0.02 sec)


RESERVATION2

mysql> insert into reservation2 values(10201,'2012-02-20 10:20:25',05,'HYD',9654 235242);Query

OK, 1 row affected (0.03 sec)

mysql> insert into reservation2 values(10202,'2012-02-22 10:22:25',05,'HYD',9654 232451);Query

OK, 1 row affected (0.02 sec)

mysql> insert into reservation2 values(10203,'2012-03-22 10:30:25',05,'DELHI',96 54587960);Query

OK, 1 row affected (0.01 sec)

mysql> insert into reservation2 values(10204,'2013-03-22 11:30:25',05,'CHENNAI', 9845761254);Query OK,

1 row affected (0.02 sec)

Q1:Display unique PNR_NO of all reservation

Mysql>Select DISTINCT PNR_NO from Reservation;

PNR_No
10201
10202
10203
10204
Q2:Display the ticket numbers and names of all the passengers.

mysql> select t.ticketno,p.name from passengerticket t,passenger2 p where t.passportid = p.passportid;


Q3:Find the ticket numbers of the passengers whose name start with ‘r’ and ends with ‘h’.

MySQL> SELECT Name FROM Passenger WHERE name LIKE ‘R%H’

Name
Rajesh
Ramesh
Ramesh
EX.NO:2(ii) IMPLEMENTATION OF JOINS

Date:

AIM:

To study the various joins in MYSQL and implement them on the database.

MySQL JOINS

MySQL JOINS are used with SELECT statement. It is used to retrieve data from multiple tables. It
is performed whenever you need to fetch records from two or more tables.

There are three types of MySQL joins:


o MySQL INNER JOIN (or sometimes called simple join)
o MySQL LEFT OUTER JOIN (or sometimes called LEFT JOIN)
o MySQL RIGHT OUTER JOIN (or sometimes called RIGHT JOIN)

MySQL Inner JOIN (Simple Join)

The MySQL INNER JOIN is used to return all rows from multiple tables where the join condition
is satisfied. It is the most common type of join.

Syntax:

SELECT columns FROM table1 INNER JOIN table2 ON

table1.column = table2.column;

Query:

Consider two tables "officers" and "students", having the following data.
Q1: Display the Officer name,address and student course name by implementing a inner join.

MySQL Left Outer Join

The LEFT OUTER JOIN returns all rows from the left hand table specified in the ON condition
and only those rows from the other table where the join condition is fulfilled.

Syntax:

SELECT columns FROM table1 LEFT [OUTER] JOIN table2 ON table1.column = table2.colum
n;

Q2: Display the Officer name,address and student course name by implementing a left outer

join.
MySQL Right Outer Join

The MySQL Right Outer Join returns all rows from the RIGHT-hand table specified in the ON
condition and only those rows from the other table where he join condition is fulfilled.

Syntax:

SELECT columns FROM table1 RIGHT [OUTER] JOIN table2 ON table1.column =

table2.column;

Q3: Display the Officer name,address and student course name by implementing a Right outer

join.
EX.NO:3(i) CREATION OF EMPLOYEE DATABASE TO SET VARIOUS
CONSTRAINTS
Date:

AIM:

To create an employee database to set various constraints

CONSTRAINTS:
Constraints are used to specify rules for the data in a table. If there is any violation between the constraint and
the data action, the action is aborted by the constraint. It can be specified when the table is created (using
CREATE TABLE statement) or after the table is created (using ALTER TABLE statement).

1. NOT NULL:
When a column is defined as NOTNULL, then that column becomes a mandatory column. It implies that a
value must be entered into the column if the record is to be accepted for storage in the table.

Syntax:
CREATE TABLE Table_Name (column_name data_type (size) NOT NULL, );

Example:
CREATE TABLE student (sno integer(3) NOT NULL, name varchar(10));

2. UNIQUE:
The purpose of a unique key is to ensure that information in the column(s) is unique i.e. a value entered in
column(s) defined in the unique constraint must not be repeated across the column(s). A table may have many
unique keys.

Syntax:
CREATE TABLE Table_Name(column_name data_type(size) UNIQUE, ….);

Example:
CREATE TABLE student (sno integer(3) UNIQUE, name varchar(10));
3. CHECK:

Specifies a condition that each row in the table must satisfy. To satisfy the
constraint, each row in the table must make the condition either TRUE or unknown (due to a
null).

Syntax:
CREATE TABLE Table_Name(column_name data_type(size) CHECK(logical
expression), ….);

Example:
mysql> CREATE TABLE Persons (
-> ID int NOT NULL,
-> LastName varchar(255) NOT NULL,
-> FirstName varchar(255),
-> Age int,
-> CHECK (Age>=18)
-> );
Query OK, 0 rows affected (0.09 sec)

4. PRIMARY KEY:

A field which is used to identify a record uniquely. A column or


combination of columns can be created as primary key, which can be used as a reference
from other tables. A table contains primary key is known as Master Table.
 It must uniquely identify each record in a table.
 It must contain unique values.
 It cannot be a null field.
 It cannot be multi port field.
 It should contain a minimum no. of fields necessary to be called unique.
Syntax:

CREATE TABLE Table_Name(column_name data_type(size) PRIMARY KEY,….);

Example:

CREATE TABLE faculty (fcode integer(3) PRIMARY KEY, fname varchar(10));

5. FOREIGN KEY:

The foreign key is used to link one or more than one table together. It is also known as the referencing key. A
foreign key matches the primary key field of another table. It means a foreign key field in one table refers to
the primary key field of the other table. It identifies each row of another table uniquely that maintains
the referential integrity in MySQL.

A foreign key makes it possible to create a parent-child relationship with the tables. In this relationship, the
parent table holds the initial column values, and column values of child table reference the parent column values.
MySQL allows us to define a foreign key constraint on the child table.

MySQL defines the foreign key in two ways:

1. Using CREATE TABLE Statement


2. Using ALTER TABLE Statement

Syntax:

[CONSTRAINT constraint_name]
FOREIGN KEY [foreign_key_name] (col_name, ...)
REFERENCES parent_tbl_name (col_name,...)
ON DELETE referenceOption
ON UPDATE referenceOption

In the above syntax, we can see the following parameters:

constraint_name: It specifies the name of the foreign key constraint. If we have not provided the constraint
name, MySQL generates its name automatically.

col_name: It is the names of the column that we are going to make foreign key.
parent_tbl_name: It specifies the name of a parent table followed by column names that reference the foreign
key columns.

Reference_option: It is used to ensure how foreign key maintains referential integrity using ON DELETE and
ON UPDATE clause between parent and child table.

MySQL contains five different referential options, which are given below:

CASCADE: It is used when we delete or update any row from the parent table, the values of the matching
rows in the child table will be deleted or updated automatically.

SET NULL: It is used when we delete or update any row from the parent table, the values of the foreign key
columns in the child table are set to NULL.

RESTRICT: It is used when we delete or update any row from the parent table that has a matching row in the
reference(child) table, MySQL does not allow to delete or update rows in the parent table.

NO ACTION: It is similar to RESTRICT. But it has one difference that it checks referential integrity after
trying to modify the table.

SET DEFAULT: The MySQL parser recognizes this action. However, the InnoDB and NDB tables both
rejected this action.

Example:
Table: customer

CREATE TABLE customer (


ID INT NOT NULL,
Name varchar(50) NOT NULL,
City varchar(50) NOT NULL,
PRIMARY KEY (ID)
);

Table: contact

CREATE TABLE contact ( ID INT, Customer_Id INT,


Customer_Info varchar(50) NOT NULL, Type varchar(50) NOT NULL,
CONSTRAINT fk_customer FOREIGN KEY (Customer_Id)
REFERENCES customer(ID)
ON DELETE CASCADE
ON UPDATE CASCADE
);
Defining integrity constraints in the alter table command:

Syntax:
ALTER TABLE Table_Name ADD PRIMARY KEY (column_name);

Example:
ALTER TABLE student ADD PRIMARY KEY (sno);

(Or)

Syntax:
ALTER TABLE table_name ADD CONSTRAINT constraint_name
PRIMARY KEY(colname)

Example:
ALTER TABLE student ADD CONSTRAINT SN PRIMARY KEY(SNO)

Dropping integrity constraints in the alter table command:

Syntax:
ALTER TABLE Table_Name DROP constraint_name;

Example:
ALTER TABLE student DROP PRIMARY KEY;
(or)
Syntax:
ALTER TABLE student DROP CONSTRAINT constraint_name;

Example:
ALTER TABLE student DROP CONSTRAINT SN;
6. DEFAULT :

The DEFAULT constraint is used to insert a default value into a column. The
default value will be added to all new records, if no other value is specified.

Syntax:

CREATE TABLE Table_Name(col_name1,col_name2,col_name3


DEFAULT ‘<value>’);

Example:
CREATE TABLE Persons1 (
ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int,
City varchar(255) DEFAULT 'Sandnes'
);
QUERIES

Q1. Create a table called EMP with the following structure.

Name Type
---------- ----------------------
EMPNO INTEGER(6)
ENAME VARCHAR(20)
JOB VARCHAR(10)
DEPTNO INTEGER(3)
SAL INTEGER(7)
Allow NULL for all columns except ename and job.

Solution:
1.Understand create table syntax.
2.Use the create table syntax to create the said tables.

mysql> CREATE TABLE EMP(EMPNO INTEGER(6),ENAME VARCHAR(20),JOB


VARCHAR(10),DEPTNO INTEGER(3),SAL INTEGER(7));
Query OK, 0 rows affected (0.14 sec)

Q2. Add constraints to check, while entering the empid value (i.e) empid > 100 and implement not null
constraints.

mysql> CREATE TABLE EMPLOYEE (EMPID int NOT NULL, LastName varchar(255) NOT
NULL,FirstName varchar(255), Age int, CHECK (Age>=18));
Query OK, 0 rows affected (0.16 sec)

Q3:Define the field DEPTNO as unique.

mysql> alter table employee1 add column deptno int unique;


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

Q4:Create a primary key constraint for the table(EMPNO).

mysql> create table empl(empno integer primary key,ename varchar(25));


Query OK, 0 rows affected (0.13 sec)

Q5:Write queries to implement and practice constraints.

1. ‘NOT NULL’ Constraint

mysql> CREATE TABLE Employe(Id INTEGER, Name TEXT NOT NULL, Hometown VARCHAR(40));
Query OK, 0 rows affected (0.17 sec)

mysql> INSERT INTO Employe VALUES(1,'John','Mumbai');


Query OK, 1 row affected (0.05 sec)

mysql> INSERT INTO Employe VALUES(2,NULL,'Delhi');


ERROR 1048 (23000): Column 'Name' cannot be null.

2. ‘UNIQUE’ Constraint

mysql> CREATE TABLE Employe1(Id INTEGER, Name varchar(20) UNIQUE, Hometown


VARCHAR(40));
Query OK, 0 rows affected (0.19 sec)

mysql> INSERT INTO Employe1 VALUES(1,'John','Mumbai');


Query OK, 1 row affected (0.13 sec)

mysql> INSERT INTO Employe1 VALUES(2,'Jack','Mumbai');


Query OK, 1 row affected (0.06 sec)

mysql> INSERT INTO Employe1 VALUES(3,'Jack','Mumbai');


ERROR 1062 (23000): Duplicate entry 'Jack' for key 'Name'.

3. ‘CHECK’ Constraint

mysql> CREATE TABLE Employe2(Id INTEGER, Name varchar(30), HomeTown VARCHAR(40), Age int,
CHECK (Age>=21));
Query OK, 0 rows affected (0.22 sec)

mysql> INSERT INTO Employe2 VALUES(1,'John','Mumbai',25);


Query OK, 1 row affected (0.13 sec)
EX.NO:3(ii) CREATION OF VIEWS, INDEXING AND SAVEPOINT
Date:

AIM:

To create a view, indexing and use savepoint in Mysql database.

MySQL View
A view is a database object that has no values. Its contents are based on the base table. It contains rows and
columns similar to the real table. In MySQL, the View is a virtual table created by a query by joining one or more
tables. It is operated similarly to the base table but does not contain any data of its own. The View andtable
have one main difference that the views are definitions built on top of other tables (or views). If any changes occur
in the underlying table, the same changes reflected in the View also.

Syntax

CREATE [OR REPLACE] VIEW view_name AS

SELECT columns

FROM tables

[WHERE conditions];

Q1: Create a name for view for the ‘courses’ table in databases.

CREATE VIEW trainer AS SELECT course_name, trainer FROM courses;


MySQL Update VIEW

In MYSQL, the ALTER VIEW statement is used to modify or update the already created VIEW without
dropping it.
Syntax:

ALTER VIEW view_name AS


SELECT columns
FROM table
WHERE conditions;

Q2:Alter the already created VIEW name "trainer" by adding a new column.
MySQL Drop VIEW

It is used to drop the existing VIEW by using the DROP VIEW statement.

Syntax

DROP VIEW [IF EXISTS] view_name;

Q3: Drop the existing VIEW by using the DROP VIEW statement.

DROP VIEW trainer;

Q4: The organization wants to display only the details of the employees those who are ASP.

Solution:

1. Create a view on emp table named managers

2. Use select from clause to do horizontal portioning

Q5: The organization wants to display only the details like empno, empname,of the employees. (Vertical
portioning)

Solution:
1. Create a view on emp table named general

2. Use select from clause to do vertical partioning.


Q6: Display all the views generated.
CREATE INDEX statement
Syntax

CREATE TABLE t_index(


col1 INT PRIMARY KEY,
col2 INT NOT NULL,
col3 INT NOT NULL,
col4 VARCHAR(20),
INDEX (col2,col3)
);

CREATE INDEX [index_name] ON [table_name] (column names)

Example

mysql> CREATE INDEX ind_1 ON t_index(col4);

Q9:create an index for the jobTitle column by using the CREATE INDEX statement.

mysql> create index jobtitle on emp(job);


Query OK, 6 rows affected (0.31 sec)
Records: 6 Duplicates: 0 Warnings: 0

mysql> explain select empno,ename,sal from emp where job='AP';


+ + + + + + + + + + +
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+ + + + + + + + + + +
| 1 | SIMPLE | emp | ref | jobtitle | jobtitle | 15 | const | 2 | Using where |
+ + + + + + + + + + +
1 row in set (0.13 sec)
SAVEPOINT

The SAVEPOINT statement is used to set a save point for the transaction with the specified name. If a save
point with the given name already exists the old one will be deleted.

Syntax:

Savepoint savepoint_name;
Q10: Use savepoint command, Transaction update the age values of all the employees
in the emp table .

mysql> INSERT INTO EMP1 VALUES('Krishna', 'Sharma', 19, 'M',


2000),('Raj', 'Kandukuri', 20, 'M', 7000),('Ramya', 'Ramapriya', 25, 'F',
5000);
Query OK, 3 rows affected (0.17 sec)
Records: 3 Duplicates: 0 Warnings: 0
EX.NO:4 DATABASE PROGRAMMING USING IMPLICIT CURSOR & EXPLICIT CURSOR
Date:

AIM:

To implement a database programming using implicit cursors and explicit cursor.

CURSOR

• A cursor is a pointer to this context area. PL/SQL controls the context area through a cursor. A cursor
holds the rows (one or more) returned by a SQL statement. The set of rows the cursor holds is referred to
as the active set.

• To handle a result set inside a stored procedure, you use a cursor. A cursor allows you to iterate a set of
rows returned by a query and process each row accordingly.

1. Implicit Cursors

 Auto-created by Oracle when MYSQL is executed if there is no explicit cursor used.


 Users or programmers cannot control the information or programs in it
 Associated with INSERT, UPDATE and DELETE types of DML operation statements
 Attributes: SQL%FOUND, SQL%NOTFOUND, %ISOPEN, %ROWCOUNT
2. Explicit Cursors

 User-defined cursors which help to gain more control over the context part.
 It is defined in the declaration area of the SQL block.
 Created on SELECT statements that returns multiple records.
 Attributes: SQL%FOUND, SQL%NOTFOUND, %ISOPEN, %ROWCOUNT.

• Implicit Cursor is associated with following DML Statements

INSERT,

UPDATE and

DELETE

Attribute Name Description

%ISOPEN It is true if cursor is open and FALSE if cursor is not open or cursor is closed.
It is used only with Explicit Cursors.
%FOUND TRUE if at least one row was processed or a record was fetched successfully
from the opened cursor and FALSE otherwise.
%NOTFOUND TRUE if no row were processed or if record was not fetched successfully and
FALSE otherwise.
%ROWCOUNT It returns the number of rows/records processed by a cursor Consider the
following tables to complete the following assignment.

Syntax :
DECLARE cursor_name CURSOR FOR select_statement;

1. Open a cursor statement : For open a cursor we must use the open statement.If we want to
fetch rows from it you must open the cursor.
Syntax : OPEN cursor_name;

2. Cursor fetch statement : When we have to retrieve the next row from the cursor and move
the cursor to next row then you need to fetch the cursor.
Syntax : FETCH cursor_name INTO var_name;

If any row exists, then the above statement fetches the next row and cursor pointer moves ahead
to the next row.
3. Cursor close statement : By this statement closed the open cursor.
Syntax: CLOSE_name;
By this statement we can close the previously opened cursor. If it is not closed explicitly then a
cursor is closed at the end of compound statement in which that was declared.

EXPLICIT CURSORS
Q1: Write a MYSQL program to concat empno,empname details from
employee table using EXPLICT CURSOR
Delimiter $$
Create procedure p3(in_customer_id int)
begin
declare v_id int;
declare v_name varchar(20);
declare v_finished integer default 0;
declare c1 cursor for select empno,ename from emp where empno=in_customer_id;
declare continue handler for NOT FOUND set v_finished=1;
open c1;
std:LOOP
fetch c1 into v_id,v_name;
if v_finished=1 then
leave std;
end if;
select concat(v_id,v_name);
IMPLICIT CURSORS

Q1:Write a PL/SQL code for calculating totalcount of teacher in TUTOR table using
IMPLICIT CURSOR.

CREATE TABLE TUTOR(


CODE INT NOT NULL,
SUBJECT VARCHAR(15) NOT NULL,
TEACHER VARCHAR(15),
REVIEWS VARCHAR (10) NOT NULL,
PRIMARY KEY (CODE)
7 );

SQL>INSERT INTO TUTOR (CODE,SUBJECT,TEACHER,REVIEWS) VALUES (1, 'Automation', 'Mukul',


'five stars');
1 row created.

SQL> INSERT INTO TUTOR (CODE,SUBJECT,TEACHER,REVIEWS) VALUES (4, 'PLSQL', 'Anand',


'four stars');
1 row created.

SQL> INSERT INTO TUTOR (CODE,SUBJECT,TEACHER,REVIEWS) VALUES (2, 'Performance',


'Arvind', 'four stars');
1 row created.

SQL> set serveroutput on;


SQL> DECLARE
total_count number(30);
BEGIN
UPDATE TUTOR SET TEACHER = 'Zen' where CODE = 1;
IF sql%notfound THEN
dbms_output.put_line('no subjects fetched');
ELSEIF sql%found THEN
total_count := sql%rowcount;
EX.NO:5 IMPLEMENTATION OF EXCEPTION HANDLING
Date:

AIM:

To implement a PL/SQL block that handles all types of exceptions.

MYSQL HANDLER:

MySQL handler to handle errors encountered in stored procedures.

When an error occurs inside a stored procedure, it is important to handle it appropriately, such as continuing
or exiting the current code block’s execution, and issuing a meaningful error message.

MySQL provides an easy way to define handlers that handle from general conditions such as warnings or
exceptions to specific conditions e.g., specific error codes.

Declaring a handler

DECLARE action HANDLER FOR condition_value statement;

The action accepts one of the following values:


1.CONTINUE : the execution of the enclosing code block ( BEGIN … END ) continues.
2.EXIT : the execution of the enclosing code block, where the handler is declared, terminates.

The condition_value specifies a particular condition or a class of conditions that activate the handler. The
condition_value accepts one of the following values:
1.A MySQL error code.
2.A standard SQLSTATE value. Or it can be an SQLWARNING , NOTFOUND or SQLEXCEPTION condition,
which is shorthand for the class of SQLSTATE values. The NOTFOUND condition is used for a cursor or
SELECT INTO variable_list statement.
3.A named condition associated with either a MySQL error code or SQLSTATE value.
The statement could be a simple statement or a compound statement enclosing by the BEGIN and END
keywords.
EXAMPLES:

DECLARE CONTINUE HANDLER FOR SQLEXCEPTION SELECT 'Error occured';


DECLARE CONTINUE HANDLER FOR SQLEXCEPTION SET IsError=1;
DECLARE EXIT HANDLER FOR SQLEXCEPTION SET IsError=1;
DECLARE EXIT HANDLER FOR SQLSTATE '23000' SET IsError = 1;

Q1:Insert a duplicate value into EmpID column to check the continue handler SQL exception

CREATE DATABASE Employee;

CREATE TABLE Employee.tbl_EmployeeDetails


(
EmpID INTEGER
,EmpName VARCHAR(50)
,EmailAddress VARCHAR(50)
,CONSTRAINT pk_tbl_EmployeeDetails_EmpID PRIMARY KEY (EmpID)
);
Sample program

DELIMITER //
CREATE PROCEDURE Employee.usp_InsertEmployeeDetails
(
InputEmpID INTEGER
,InputEmpName VARCHAR(50)
,InputEmailAddress VARCHAR(50)
)
BEGIN
DECLARE CONTINUE HANDLER FOR SQLEXCEPTION SELECT 'Error occured';
INSERT INTO Employee.tbl_EmployeeDetails
(
EmpID
,EmpName
,EmailAddress
)
VALUES
(
InputEmpID
,InputEmpName
,InputEmailAddress
);
SELECT *FROM Employee.tbl_EmployeeDetails;

END
// DELIMITER ;
Execution
CALL Employee.usp_InsertEmployeeDetails (1,'Anvesh','[email protected]');
CALL Employee.usp_InsertEmployeeDetails (1,'Roy','[email protected]');
[The execution didn’t stop by error, and it continued for another part.]
Q2:Insert a duplicate value into EmpID column to check the exit handler SQL exception

Sample program

DELIMITER //
CREATE PROCEDURE Employee.exithandler(
InputEmpID INTEGER
,InputEmpName VARCHAR(50)
,InputEmailAddress VARCHAR(50)
)
BEGIN
DECLARE EXIT HANDLER FOR SQLEXCEPTION SELECT 'Error occured';
INSERT INTO Employee.tbl_EmployeeDetails
(
EmpID
,EmpName
,EmailAddress
)
VALUES
(
InputEmpID
,InputEmpName
,InputEmailAddress
);
SELECT *FROM Employee.tbl_EmployeeDetails;
END
// DELIMITER ;
Execution
CALL Employee.exithandler(1,'Roy','[email protected]');

The Result is an only error message, and you cannot find two results as we defined EXIT to exit the
code when an error occurred.
Q3:create a output parameter and store 1 if any error occurred using continue handler.

Sample program

DELIMITER //
CREATE PROCEDURE Employee.sethandler(
InputEmpID INTEGER
,InputEmpName VARCHAR(50)
,InputEmailAddress VARCHAR(50)
,out IsError INTEGER
)
BEGIN
DECLARE CONTINUE HANDLER FOR SQLEXCEPTION SET IsError=1;

INSERT INTO Employee.tbl_EmployeeDetails


(
EmpID
,EmpName
,EmailAddress
)
VALUES
(
InputEmpID
,InputEmpName
,InputEmailAddress
);
SELECT *FROM Employee.tbl_EmployeeDetails;
END
// DELIMITER ;
Execution

CALL Employee.sethandler (1,'Roy','[email protected]',@IsError);


SELECT @IsError;
EX.NO:6 IMPLEMENTATION OF PROCEDURES AND FUNCTIONS
Date:

AIM:

To create a database and apply Procedures and Functions in Mysql database

PROCEDURES

A procedure (often called a stored procedure) is a collection of pre-compiled SQL statements stored
inside the database. It is a subroutine or a subprogram in the regular computing language. A procedure always
contains a name, parameter lists, and SQL statements.

Syntax

DELIMITER &&
CREATE PROCEDURE procedure_name [[IN | OUT | INOUT] parameter_name datatype [, parameter
datatype]) ]
BEGIN
Declaration_section
Executable_section
END &&
DELIMITER ;

MySQL procedure parameter has one of three modes:

IN parameter

It is the default mode. It takes a parameter as input, such as an attribute. When we define it, the calling program has
to pass an argument to the stored procedure. This parameter's value is always protected.

OUT parameters

It is used to pass a parameter as output. Its value can be changed inside the stored procedure, and the changed (new)
value is passed back to the calling program. It is noted that a procedure cannot access the OUT parameter's initial value
when it starts.
INOUT parameters

It is a combination of IN and OUT parameters. It means the calling program can pass the argument, and the
procedure can modify the INOUT parameter, and then passes the new value back to the calling program.

Q1:create a procedure without any parameters for student marks.

mysql> create database proc;


Query OK, 1 row affected (0.15 sec)

mysql> CREATE TABLE studentMarks (stud_id SMALLINT(5) NOT NULL AUTO_INCREMENT PRIMARY
KEY, total_marks INT, grade VARCHAR(5));
Query OK, 0 rows affected (0.25 sec)

mysql> INSERT INTO studentMarks(total_marks, grade) VALUES(450, 'A'), (480, 'A+'), (490, 'A++'), (440,
'B+'),(400, 'C+'),(380,'C'),(250, 'D'),(200,'E'),(100,'F'),(150,'F'),(220, 'E');
Query OK, 11 rows affected (0.14 sec)
Records: 11 Duplicates: 0 Warnings: 0

mysql> DELIMITER $$
mysql> CREATE PROCEDURE GetStudentData()
-> BEGIN
-> SELECT * FROM studentMarks;
-> END$$
Query OK, 0 rows affected (0.11 sec)

mysql> Delimiter ;
mysql> CALL GetStudentData();
Q2:create a procedure to fetch the details of students with the student ID being passed as an input
parameter.

DELIMITER //

CREATE PROCEDURE employee.StudentName(IN studentId INT)

BEGIN

SELECT * FROM studentMarks where stud_id = studentId;

END //

DELIMITER ;

Mysql>call employee.StudentName(1);
Q3:Create a procedure to calculate the average marks of all the students from the studentMarks
table and return the average as an OUT field.

DELIMITER //
CREATE PROCEDURE employee.AverageMarks(OUT average DECIMAL(5,2))
BEGIN
SELECT AVG(total_marks) INTO average FROM studentMarks;
END //
DELIMITER ;

mysql> call employee.AverageMarks(@average_marks);


mysql> SELECT @average_marks;

Q4:Create a procedure that takes an initial value of the counter and increment it with a given number.

DELIMITER //

CREATE PROCEDURE employee.UpdateCounter(INOUT counter INT, IN increment INT)

BEGIN

SET counter = counter + increment;

END //

DELIMITER ;

mysql> SET @counter=10;


Query OK, 0 rows affected (0.00 sec)

mysql> call employee.UpdateCounter(@counter,3);


Query OK, 0 rows affected (0.05 sec)

mysql> select @counter;

Q5:write a procedure to take studentId and depending on the studentMarks we need to return the class
according to the below criteria.

Marks >= 400 : Class – First Class


Marks >= 300 and Marks < 400 – Second Class
Marks < 300 – Failed

DELIMITER $$

CREATE PROCEDURE employee.StudentClass(IN studentId INT, OUT class VARCHAR(20))

BEGIN

DECLARE marks INT DEFAULT 0;

SELECT total_marks INTO marks FROM studentMarks WHERE stud_id = studentId;

IF marks >= 400 THEN

SET class = "First Class";

ELSEIF marks >=300 AND marks < 400 THEN

SET class = "Second Class";

ELSE

SET class = "Failed";


END IF;

END$$

DELIMITER ;

mysql> CALL employee.StudentClass(1,@class);


Query OK, 0 rows affected (0.05 sec)

mysql> select @class;


FUNCTIONS:

In MySQL, a function is a stored program that you can pass parameters into and then return a value.

MySQL has many built-in functions.

This reference contains string, numeric, date, and some advanced functions in MySQL.

Syntax

DELIMITER $$

CREATE FUNCTION name_of_function(

parameter1,

parameter2,…

RETURNS datatype

[NOT] DETERMINISTIC

BEGIN

-- code of statements to be executed

END $$

DELIMITER ;

Q6:write a function to call them by passing the age variable instead of statically declaring and initializing
in the example .

DELIMITER $$
CREATE FUNCTION isEligible(
age INTEGER
)
RETURNS VARCHAR(20)
DETERMINISTIC
BEGIN
IF age > 18 THEN
RETURN ("yes");
ELSE
RETURN ("No");
END IF;
END$$
DELIMITER ;

mysql> SELECT isEligible(20);

Q6:write a function return the number of months between the current date and the supplied date.

DELIMITER $$
CREATE FUNCTION getMonths(sampledate date) RETURNS int DETERMINISTIC
BEGIN
DECLARE currentDate DATE;
Select current_date()into currentDate;
RETURN (12 * (YEAR(currentDate)
- YEAR(sampledate))
+ (MONTH(currentDate)
- MONTH(sampledate)));
END
$$
DELIMITER ;

mysql> ALTER TABLE EMP ADD COLUMN joining_date DATE DEFAULT "2019-05-01";
Query OK, 6 rows affected (0.67 sec)
Records: 6 Duplicates: 0 Warnings: 0
EX.NO:7 STUDY THE BASICS OF FRONT END TOOLS
Date:

AIM:

To study the basics of front end Tools using Microsoft Access

MICROSOFT ACCESS

Microsoft Access is a Database Management System offered by Microsoft. It uses the Microsoft Jet
Database Engine and comes as a part of the Microsoft Office suite of application.

Microsoft Access offers the functionality of a database and the programming capabilities to create easy to navigate
screens (forms). It helps you analyze large amounts of information, and manage data efficiently.

Database File:

It is a file which stores the entire database. The database file is saved to your hard drive or other storage devices.

Datatypes:

Datatypes are the properties of each field. Every field has one datatype like text, number, date, etc.

Table

 A Table is an object which stores data in Row & Column format to store data.
 A Table is usually related to other tables in the database file.
 Each column must have Unique name
 We can also define Primary Key in a table.

Query

 Queries answer a question by selecting and sorting and filtering data based on search criteria.
 Queries show a selection of data based on criteria (limitations) you provide.
 Queries can pull from one or more related Tables and other Queries.
 Types of Query can be SELECT, INSERT, UPDATE, DELETE.
Form

 A form is a database object that you can use to create a user interface for a database application.
 Forms help you to display live data from the table. It mainly used to ease the process of data entry or editing.

Report

 A report is an object in desktop databases primarily used for formatting, calculating, printing, and
summarizing selected data.
 You can even customize the report’s look and feel.

Macros

Macros are mini computer programming constructs. They allow you to set up commands and processes in your forms,
like, searching, moving to another record, or running a formula.

Modules:

Modules are procedures(functions) which you can write using Visual Basic for Applications (VBA).

Microsoft Access Data Types

MS Access common data types are listed below:

Type of
Description Size
Data
Text, including numbers which does not need calculation.
Short Text Up to 255 characters.
(e.g., Mobile numbers).
This data type is used for lengthy text or alphanumeric
Long Text Maximum 63, 999 characters.
data.
Numeric data type used for storing mathematical
Number 1, 2, 4, 8, and 16 bytes.
calculations.
Date/Time Store Date/time for the years 100 through 9999. 8 bytes.
It allows you to store currency values and numeric data
Currency 8 bytes.
with one to four decimal places.
Assign a unique number or assigned by Microsoft Access
Auto Four bytes (16 bytes if it is set as a
when any new record is created. Usually used as the
Number Replication ID).
primary key
Yes/No It only stores logical values Yes and No. 1 bit
It stores files, such as digital photos. Multiple files can be Up to 2
Attachment
attached per record. GB Data can be stored.
OLE objects can store audio, video, other Binary Large Up to 2
OLE objects
Objects. GB data can be stored.

Each part of a Hyperlink data type


Text or combinations of text and numbers stored. That text
Hyperlink allows you to store a maximum 2048
is used as hyperlink address.
characters.
Helps you to create an expression that uses data from one You can create an expression which
Calculated
or more fields. uses data from one or more fields.

Benefits for using MS Access application:

 Access offers a fully functional, relational database management system in minutes.


 Easy to import data from multiple sources into Access
 You can easily customize Access according to personal and company needs
 Microsoft Access online works well with many of the development languages that work on Windows OS
 It is robust and flexible, and it can perform any challenging office or industrial database tasks.
 MS-Access allows you to link to data in its existing location and use it for viewing, updating, querying, and
reporting.
 Allows you to create tables, queries, forms, and reports, and connect with the help of Macros
 Macros in Access is a simple programming construct with which you can use to add functionality to your
database.
 Microsoft Access online can perform heterogeneous joins between various data sets stored across different
platforms

Basic Access Objects


Access consists of four main database objects: Tables, Queries, Forms, and Reports. Each object has at
least two views, Design and "Data". The Design View is where we build the structure of that database
object. The data view shows the output of the data and is different for each object. Tables and Queries
have a Datasheet View, Forms have a Form View, and Reports have a Report View, or a Print Preview
view. Each kind of object has its own purpose.

Tables
Tables store data. The Tables are the true 'database' (base of data). These need to be created and
properly linked (related) in order to effectively use the other Access tools. Tables are the core of your
database, everything else in Access depends on the Tables.
The Design View of a Table allows you to create and modify:
‐ Field Names (the column headings)
The type of data stored in a field (Data Type). In this workshop we use:
Data Type
Description
‐ The type of data stored in a field (Data Type).

‐ Descriptions, which will be displayed in the status bar in the Data view of Forms.
- And the Properties of each field, such as how many characters can be entered (text field size),or
how the data is formatted (05/05/22 or May 5, 2022).

The Datasheet View of a Table allows you to create and modify the data within a grid structure based
on the settings in the Design View.
Vocabulary
A collection of fields make up a record. A collection of records make up a Table. A collection of
Tables make up a database
Field – One column of a Table common to all the records
Record – One row of a Table containing all data about a particular entry
Table – One set of related data
Database – Structured collection of related Tables

Queries
Queries show a selection of data based on criteria (limitations) you provide. Queries can pull from one
or more related Tables and/or other Queries.
The Datasheet View of a Query looks like a Table. All data added or modified in a Query, will be saved
in the Table. The Design View is where the structure of the Query is created. This is where we choose
the record sources and fields, and set the sort order and criteria.
Forms
Most Forms display one record at a time, in a formatted user‐friendly environment. You can build your
Form so it will display multiple records. As you develop Forms you can create navigation buttons, insert
graphics, and change the colors to display everything consistently. Forms have three basic views: Design
View, Layout View, and Form View.
Your record source can be a Table or Query. If we want to *all* the patients use the Table; if we only
want to see Dr. Edward's Patients, use a Query.

The data entered or modified in a Form is automatically saved to the Table. The Table is the true
location of the data; the Form is a "pretty" way to view/modify/create the data.
Reports
Reports are designed to create an organized output of data from your database. With a Report, you can
group and summarize information. You can't edit the data in a Report, but if you make the
modifications in the Table, Query, or Form you will see the results when you open the Report again.
Reports have four basic views: Report View, Print Preview, Layout View, and Design View.
EX.NO:8 CREATION OF DATABASE TRIGGERS
Date:

AIM:

To create a database and apply triggers in Mysql database.

MYSQL TRIGGER

In MySQL, a trigger is a stored program invoked automatically in response to an event such as insert, update,
or delete that occurs in the associated table. For example, you can define a trigger that is invoked automatically
before a new row is inserted into a table.

MySQL supports triggers that are invoked in response to the INSERT, UPDATE or DELETE event.

The SQL standard defines two types of triggers: row-level triggers and statement-level triggers.

 A row-level trigger is activated for each row that is inserted, updated, or deleted. For example, if a table has
100 rows inserted, updated, or deleted, the trigger is automatically invoked 100 times for the 100 rows
affected.
 A statement-level trigger is executed once for each transaction regardless of how many rows are inserted,
updated, or deleted.

MySQL supports only row-level triggers. It doesn’t support statement-level triggers.

Types of Triggers in MySQL


1. Before Insert: It is activated before the insertion of data into the table.
2. After Insert: It is activated after the insertion of data into the table.
3. Before Update: It is activated before the update of data in the table.
4. After Update: It is activated after the update of the data in the table.
5. Before Delete: It is activated before the data is removed from the table.
6. After Delete: It is activated after the deletion of data from the table.
Syntax

CREATE TRIGGER trigger_name

(AFTER | BEFORE) (INSERT | UPDATE | DELETE)

ON table_name FOR EACH ROW

BEGIN

--variable declarations

--trigger code

END;

mysql> CREATE TABLE employeee(


-> name varchar(45) NOT NULL,
-> occupation varchar(35) NOT NULL,
-> working_date date,
-> working_hours varchar(10)
-> );
Query OK, 0 rows affected (0.09 sec)

mysql> INSERT INTO employeee VALUES


-> ('Robin', 'Scientist', '2020-10-04', 12),
-> ('Warner', 'Engineer', '2020-10-04', 10),
-> ('Peter', 'Actor', '2020-10-04', 13),
-> ('Marco', 'Doctor', '2020-10-04', 14),
-> ('Brayden', 'Teacher', '2020-10-04', 12),
-> ('Antonio', 'Business', '2020-10-04', 11);
Query OK, 6 rows affected (0.17 sec)
Records: 6 Duplicates: 0 Warnings: 0
Q1:create a BEFORE INSERT trigger and to insert the working_hours = 0 if someone tries to
insert working_hours < 0.

DELIMITER //
Create Trigger before_insert_empworkinghours
BEFORE INSERT ON employeee FOR EACH ROW
BEGIN
IF NEW.working_hours < 0 THEN SET NEW.working_hours = 0;
END IF;
END //

mysql> INSERT INTO employeee VALUES('Markus', 'Former', '2020-10-08', 14);

mysql> INSERT INTO employeee VALUES('Alexander', 'Actor', '2020-10-012', -13);


Create table

MySQL>CREATE TABLE BUS(BUSNO VARCHAR(10) NOT NULL, SOURCE VARCHAR(10),


DESTINATION VARCHAR(10), CAPACITY INT(2), PRIMARYKEY(BUSNO));

MySQL>INSERT INTO BUS VALUES('AP123','HYD','CHENNAI','40');

CREATE TABLE BUS_AUDIT1(ID INT NOT NULL AUTO_INCREMENT, SOURCE VARCHAR(10) NOT
NULL, CHANGEDON DATETIME DEFAULT NULL, ACTION VARCHAR(10) DEFAULT NULL, PRIMARY
KEY(ID));
Q2:create a BEFORE UPDATE trigger and to update the values

DELIMITER $$
CREATE TRIGGER BEFORE_BUS_UPDATE BEFORE UPDATE ON BUS FOR EACH ROW BEGIN
INSERT INTO BUS_AUDIT1
SET action='update', source=OLD.source, changedon=NOW();
END$$
Query OK, 0 rows affected (0.16 sec)

BEFORE UPDATE
MySQL>UPDATE BUS SET SOURCE='KERALA' WHERE BUSNO='AP123'$$
Q3:create a BEFORE INSERT trigger and to update the values

BEFORE INSERT:

DELIMITER $$;

CREATE TRIGGER BEFORE_BUS_INSERT BEFORE INSERT ON BUS

FOR EACH ROW BEGIN

INSERT INTO BUS_AUDIT1

SET action='Insert', source=NEW.source, changedon=NOW();

END$$

MYSQL>INSERT INTO BUS VALUES('AP789','VIZAG','HYDERABAD',30)$$

BEFORE DELETE

Q4:create a BEFORE DELETE trigger that inserts a new record into the salary_archives table before a
row is deleted from the salaries table.

CREATE TABLE salaries (emp_num INT PRIMARY KEY,valid_from DATE NOT NULL,amount DEC(8 ,
2 ) NOT NULL DEFAULT 0);
CREATE TABLE salary_archives (
id INT PRIMARY KEY AUTO_INCREMENT,
emp_num INT,
valid_from DATE NOT NULL,
amount DEC(18 , 2 ) NOT NULL DEFAULT 0,
deleted_time TIMESTAMP DEFAULT NOW()
);

Sample code:
DELIMITER $$
CREATE TRIGGER before_delete_salaries
BEFORE DELETE
ON salaries FOR EACH ROW
BEGIN
INSERT INTO salary_archives (emp_num, valid_from, amount)
VALUES(OLD. emp_num, OLD.valid_from, OLD.amount);
END$$
DELIMITER ;
Ex.NO:9 DATABASE DESIGN USING ER MODELING ,NORMALIZATION AND
IMPLEMENTATION FOR ANY APPLICATION
Date:

AIM:

To create Database design using ER and modeling, normalization implementation for any application.

Entity-Relationship Model
Entity-Relationship model or E R model is used to create a relationship between different attributes or
entities. It describes the structure of the database with the help of the ER Diagram or Entity Relationship Diagram.
ER model creates a simple design view of the data. It helps in creating the conceptual diagram of the database that
makes the data easier to understand.

ER Modeling is a graphical approach to database design. It uses Entity/Relationship to represent


real world objects.
An Entity is a thing or object in real world that is distinguishable from surrounding environment. For example each
employee of an organization is a separate entity. Following are some of major characteristics of entities.

 An entity has a set of properties.


 Entity properties can have values.
Ex.NO:10 CREATION OF DATABASE IN MS ACCESS
Date:

AIM:

To Create a Patient Appointment Database in MS ACCESS.

CREATION OF DATABASE

1. Open Microsoft Access


2. Choose Blank Desktop Database
3. Click on the yellow folder at the end of the File Name box and browse for the desktop
4. Use the file name: Patient Appointments
5. Click Create

Create the Patients Table


1. Click on the Create tab and choose Table Design

2. Type the first Field Name: Pt Med Rec #


a. Data Type: Text, Description: Patient's Medical Record Number
3. Enter in the rest of the fields (descriptions not necessary):
4. Set the Pt Med Rec # to be the key
a. Click on the big yellow key on the toolbar
5. Save the Table as Patients

Entering First Record


1. Turn to the Datasheet View in view menu
2. Enter our first Med Rec #: 123456
3. Press tab move to the next field

a. First Name: kkkk


b. Last Name: aaaa
c. Phone #: 123456789
No dashes
d. Birth Date: 1/1/1
If you set it as a DATE/TIME field Access will add in the "200" for 2001
Rearrange Fields
1. In Design View, move Pt Birth Date above the Pt Phone #
a. Click on the row heading, the grey box in front of the field name. Then Click/Drag the
line above the Pt Phone #
2. Switch to the Datasheet View and Save the table
a. Data saves itself, structural changes have to be saved manually
3. Enter the next record

Adding Fields
1. In Design View, create Pt Gender, Short Text field, above Pt Birth Date
a. Insert Rows from Design Tab, or from the right‐click menu
2. In Data View, enter "Male" (the whole word) for kkkk and mmmm
Enter a "trouble maker" Record
1. Enter the next record
a. Enter Gender as just one character
b. Enter birth date as March 3, 1983; it should change to 3/3/1983
c. Type in the hyphens for the phone number
2. Go to the Design view and then return to the Data view

a. Notice Jane's record moves. This is because by default Access sorts by the primary key
field. Since Pt Med Rec # is our key, every time the data is refreshed it will sort the data
by the primary key field.

Modify Field Properties – Field Size

1. In Design View, set Field Size property of Gender at the bottom of the window to be 1
a. When you save you will get the following warning message saying data may be lost. We
want this to happen, click Yes.
b. Data is lost, our Male entries should now only read M
Modify Field Properties – Input Mask

1. In Deign View, set an Input Mask for particular column name


a. Click in the Input Mash Property for particular column name
b. Click the Build button (…) at the end of the line to launch the wizard
c. In the Input Mask Wizard, particular column name is already selected. Click FINISH.
d. Save and View Results.
Create Female Patient's Query
1. Go to the Create Tab and choose Query Design .
2. In the Show Table window, push the Add button and then close the window
3. Double‐clicking on the field names to add Pt First Name, Pt Last Name, and Pt Gender
4. View Datasheet View
EX.NO:11 DATABASE CONNECTIVITY USING FRONT END TOOLS
Date:

AIM:
To create database design and implement database connectivity with Front End Tools as Ms-Access and Mysql
as a back end.

PROCEDURE

Software PreRequistes

MS-access,
Mysql server 5.1.45,
Mysql connector-connector odbc 5.1.4
Visual C++ Redistributable Packages for Visual studio 2013

Step 1: Open Mysql Command Line Client 5.1.45 ---> create Database-->create Multiple Tables--> insert values for
tables --> View the Data.
Step 2:Start -->search list--> ODBC Data Sources-->Click “User DSN”--> Mysql ODBC 5.1 Driver--> Finish.
Step 3:New Dialog Box will appear in that type DSN Name ,Server, User name,Password and select Test.
Connection is successful Dialog box will appear-->click ok.
Step 4:In Database Drop List -->select Database name--> click ok.
Step 5:Open MS-Access-->Create DB--> Select External Data--> ODBC Databases.
Step 6:New Dialog box will appear Select Link to tha Data Source by creating a linked list--->ok.
Step 7:Again New Dialog will appear Select Data Sources-->Select DSN name-->ok.
Step 8:Link Tables Dialog will appear-->select all-->ok..
Step 9:New Dialog Box will appear-->Select Unique record identifier --->click ok.

SAMPLE QUERIES:

mysql> create table Stationary(pid integer,pname varchar(25),quantity integer, rate integer(5));


Query OK, 0 rows affected (0.25 sec)

mysql> insert into stationary values(1,'pencil',5,25);


Query OK, 1 row affected (0.16 sec)

mysql> insert into stationary values(2,'pen',10,100);


Query OK, 1 row affected (0.13 sec)

mysql> create table books(bid integer,bname varchar(30),author varchar(50));


Query OK, 0 rows affected (0.20 sec)

mysql> insert into books values(3,'DBMS','silberchatz');


Query OK, 1 row affected (0.14 sec)
mysql> insert into books values('4','oops','sindhu');
Query OK, 1 row affected (0.14 sec)

mysql> create table faculty(hts integer,fname varchar(30),designation varchar(35));


Query OK, 0 rows affected (0.17 sec)

mysql> insert into faculty values(1583,'kavitha','AP');


Query OK, 1 row affected (0.14 sec)

mysql> insert into faculty values(1553,'sindhu','AP');


Query OK, 1 row affected (0.11 sec)
Report Layout View
EX.NO:12 CASE STUDY OF BIG DATA AND NOSQL
Date:

AIM:

To Study the databases of Bigdata and NOSQL

1. Introduction

Structured data is handled by traditional relational databases over the years. In traditional relational
database, data is stored in rows and columns format. Big data is combination of structured, semi-structured
and unstructured data. A lot of information is generated due to interactions on social networking sites and
mobile applica- tions. Semi-structured and unstructured data can not be stored in the form of tables as in
relational databases. These forms of data can be stored and processed by Big Data technologies only.
Moreover sql data storage is horizontally scalabale i.e. if large scale of data is to be stored and processed,
then storage capacity is to be increased only inside single server. There is limit on server capacity
enhancement. Distributed data storage, cloud storage, NoSQL and NewSQL are latest techniques to deal
with large scale of mixed data. NoSQL (Not Only SQL) term was introduced by C. Strozzi in 1998 in which
SQL interface was not used . In 2009, NoSQL was re-introduced by Johan Oskarsson in a conference on
“open-source, distributed, non-relational databases”. NoSQL data- base will not replace relational database,
rather these databases compliments each other . Atomicity, Consistency, Isolation and Durability are the
properties which are provided by relational databases. In the era of Big Data, when query response time
mat- ters a lot, then it is necessary to distribute the large scale of data. NoSQL database supports BASE
(Basically Available, Soft state, Eventual Consistency) properties. BASE prioritizes availabil- ity of data
than consistency. It also allows approximate answers provided with fast response time. Performance
requirements are not only required these days, rather many quality attributes like availability, consistency,
durability, maintainability, reliability and scalability are need of current business and research organizations.
It is easily distributed and scalable to handle large scale of data. The main characteristics of NoSQL data
storages are high availability and strong consistency . There are 120 solutions available for NoSQL
databases at present. Several research works have compared most popular solutions but in this paper, we
have compared NoSQL databases architecture. This comparison seems more effective as it completely
demonstrates real differences based on schema, query languages, consistency, availability
and response time. In this, important differences in NoSQL da- tabases are identified which can provide
guidance to researchers and practitioners to select the most appropriate solution.

Standard query language is not defined for NoSQL data stores. This is due to the fact that various NoSQL
solutions use different structure for storage and query. Researchers are able to solve it by articulating standard
query language for one category based solu- tions. It is in scope of further research to articulate and develop
standard query language for various categories.

Big Data Storage

Big data is large scale of data which is generated due to Social networks, Business organizations, interaction
and views of social connected users. It is used for important decision making in busi- ness organizations. It
is represented by 3Vs (Velocity, Variety and Volume). Velocity is the rate at which data comes from small
scale to become large scale. Variety is different types of data- structured, semi-structured and unstructured.
Volume is the amount of data which is very large in scale. Data acquisition, data analysis, data curation, data
storage and data usage are important phases of Big data mining. There are several characteristics of big data
storage- Cloud storage, query interfaces, NoSQL, NewSQL, Scalability, Consistency, Security and
Performance etc. Traditional storage can be efficiently implemented by relational databases like SQL and
processed on Weka, Java etc. Scalability is not well managed by relational databases..These can be effi-
ciently deployed for structured data. Several techniques have been articulated and implemented by researchers
to deploy large scale of data. These novel strategies to store large scale of data provide scalability with less
complexity. This is verified with the populari- ty of storage like Cloudera, MapR and NoSQL solutions.

Big data storage is provided by following three techniques [Strohbach]:

1. Distributed File Systems


2. NoSQL
3. NewSQL

Distributed File System: HDFS (Hadoop Distributed File System) is used for distributing large scale of data
on different clusters. These clusters work in parallel on chunks of data and after pro- cessing merge to form
final results. Hadoop MapReduce is de- ployed for mapping and reducing unstructured type of data.
NoSQL : This storage technique is used for data where tables in rows and columns can not be applied.
There are many NoSQL solutions available which can remove the drawbacks of relational databases, which
is explained in next section. NoSQL databases provide scalability but with the increase in scale of data,
scalabil- ity limits are reduced slightly.

NewSQL : Relational databases with novel techniques to process large scale of data comes under this
category. This is area where further research is required. The advantage of using this technique is relational
databases benefits for Big data are provided. NewSQL is used for multi-object transactions like in finance
services, where multiple objects can use concurrent transactions. NoSQL data-bases can not be deployed for
this scenario. It is expected that NewSQL is 50 times faster than simple SQL. VoltDB,Clusterix etc. are
examples of this storage technique. Query in NewSQL is in the form of relational tables but internally it can
store the recordin other format also.

NoSQL databases categories

NoSQL databases are used for many different applications. Dif- ferent categories of NoSQL databases are
defined based on these domain specific applications which are as follows:
 Column oriented
 Graph based
 Key value
 Document oriented

Column Oriented

In this storage structure, values are not stored in rows. It is stored based on the values of columns. In
traditional relational databases, values are stored in rows, so values are stored as null for columns where
values are not known. This drawback is removed by column oriented storage structures. Column data is
distributed on different clusters; hence large scale of data can be easily handled. Scalability is improved by
using this data storage technique. Many column oriented databases can be easily deployed on Mapreduce,
hence easily deployed for big data. It is most suitable for data mining applications. Column oriented
databases provide bet- ter indexing and query structure than key value databases. Google BigTable, HBase,
SciDB, Amazon SimpleDB and Cassandra are examples of column oriented database.
Row oriented data storage

ID Name Address Age


1 Abc Abc1 25
2 Xyz Xyz1 28
3 Klm Klm1 30
4 Wer Wer1 27

Column oriented data storage

BigTable

This data storage is developed by Google and uses GFS (Google File Systems). In transaction, data is written
until memtable reaches threshold value. Multiple set of data is read at once. BigTable does not support SQL like
structure. It is used in Google app engine. It manages many clusters by using CMS (Cluster Management
Systems). Data is stored in SSTable format which isa persistent and ordered map.

Cassandra
This data storage is developed by Apache Software Foundation. This storage technique is implemented in
Java. In this data storage structure, data is distributed on multiple nodes. Relational data- base format is not
followed in this storage technique, rather dynamic schema and content is used. Fault tolerance with no single
point of failure and high throughput are important features of this storage technique. Social networking sites,
banking and finance are the application areas of this storage technique. It supports SQL like query language
CQL. It is same as SQL but to implement scalability some features of SQL are not present like Joins, aggre-
gate functions. Values are stored in the form if triple (row, column, timestamp). Its throughput is consistently
better than many other databases.
HBase

It is open source implemented in Java and developed by Apache Software. It uses HTTP/REST protocol.
Storage is provided by Hadoop Distributed File System (HDFS) and Hadoop MapReduce framework.
Search engines and log data analysis are the applica- tion area of HBase.

Graph based

Social networking sites use connection amongst users to provide them information, latest views or
recommendations from connect- ed users. This information can not be stored by relational database.
Moreover, relational database works only for predefined schema, dynamic schema can be used by graph
based databases. Graph based data can be stored using nodes as users and edges as connection amongst
users. Semi-structured and unstructured data is well handled by this storage technique. Graph datbases are
not suitable for horizontal scaling i.e. when connected nodes are dis- tributed on clusters, it is very difficult
to traverse and manipulate graph. Neo4J, OrientDB and InfoGrid are examples of graph based databases.

1 2
5

3 4

Fig. : Graph based data storage

It is clear from Figure that users are represented as nodes and relationships are represented by directed
edges. These nodes are connected through direct edges and there is no need to store the index. For example,
social connected users on social network can be better represented by this storage technique.

Neo4J

It is the most popular graph based data storage. Entities are represented by nodes and relationships amongst
entities are represented by edges. Traditional relational dataset like schema is not present in this data
storage. Indexing of nodes is provided by this storage technique. It is compatible with Java, Python and
Ruby. Cypher query language is used for finding nodes and edges representations. Its application is in
various fields like storing record in healthcare.
OrientDB

Graph based and document based storage are combined in this NoSQL database. It uses the scheme- less
as well as scheme-mixed format. Sql queries can also be implemented in this data storage
technique.Social networking and recommendations are some of key application area of OrientDB.

Key Value

This data storage technique is very simple but effective. Data is stored in the form of key which have
unique value like Map or dictionary. Key-value pair structure is fast in index i.e. value can be retrieved
faster as compared to traditional relational database. Key can not be duplicate and has unique value.
Response time for query using this storage technique is very less. Data is stored with schema less
format.This storage technique is very efficient for distributed storage. In scenario where relations or
structures are required, key-value storage is not suitable. Key value store is used in Web sessions or any
user specific information sites. The reason is that user data (i.e. value) should not be accessed directly, it
must be accessed by the use of key. Dynamo from Amazon, Azure Table and Redis are examples of key
value database.

Key value data storage


In Figure , it is clearly explained that for a unique key,there is corre- sponding unique value.

DynamoDB

It is NoSQL database that provides reliable and cost effective storage. When many replics are not
available, even then reliability is provided by this data storage. It uses solid state drives (ssd) instead of
hard drives. It is implemented by using Amazon’s Dynamo model. Data is stored on multiple data centres
(at least three) to provide high reliability. It provides replication with MVCC (multi version concurrency
control). Synchronized clusters are also the main characteristics of this storage technique for repli- cas.
These nodes are having equal privileges and roles to provide fault tolerance. Thedisadvantage is that
range queries are not possible.

Oracle NoSQL

Big data storage can be well handled by Oracle NoSQL. It com- bines oracle and hadoop to store and
process unstructured data. JSON format is implemented in this database. It is very simple key-value
data storage.

Document based
Document oriented data storage

Student
{ id=101,
name=”abc”,
age=20}

Data is stored in the form of documents rather than simple row- column values. XML [eXtensible Markup
Language] or JSON [Javascript Object Notation] format is used which stores relevant information in the
form of documents. The advantage of using JSON format is that different programming object structure
can be easily mapped in this format . Document oriented data storage technique should not be used when
there are a lot of relations amongst different tables and normalization is to be incorporated. This storage
technique uses dynamic schema, the advantage is new attribute can be easily added for some documents.
This is different from relational database fixed schema structure where new attribute is to be added for all
records, if values are not known; many null values are to be added. Document based databases pro- vides
indexing based on primary key . Blogs and content man- agement systems are easily stored in document
oriented databases. MongoDB, CouchDB, OrientDB and MarkLogic are examples of document oriented
databases.

MongoDB

It is open source document oriented data storage. It works on Mas- ter-Slave storage architecture. Master
can read and write in the form of documents while slave can only read. Format for storage is BSON (more
compact format i.e. Binary JSON) which uses dynamic schema. Fault tolerance is the main feature of
MongoDB. MongoDB allows data to be organized in the form of Collections and not on tables. Querying
specified record from this collection isused by dot (.) notations. Many programming languages are sup-
ported by this storage system. It is widely used for storing records in the form of documents in Healthcare
. It can provide high throughput than many other databases.

CouchDB

It is used for implementing web interface using JSON format. It is written in Erlang and not based on
schema as in relational data- base. It is also defined as combination of unreliable clusters. Http and Rest
protocol is used in this data storage. Map and Reduce is used for deploying Big data in CouchDB.
Javascript query language is used to fetch unstructured data. High scalability and high availability are
important features of this storage structure.

Comparison of NoSQL databases categories

Several research works have compared NoSQL varieties based on real examples. In this paper, we have
compared NoSQL varieties based on storage architecture. It is very easy for reader to differen- tiate
different varieties and select storage techniques best suitable for specific application. Comparison of
NoSQL database categories is given in Table 1.

Various applications of NoSQL data storage techniques are elabo- rated in Table 1. If any application
requires social connections analysis, then graph based NoSQL should be used. Programming languages
objects can be stored using JSON in Document based storage. If query response time should be reduced
then key-value storage should be used. In applications where column values are not known, column
oriented storage is best suitable. Main differ- ences in the architecture of NoSQL databases are explained
and also most popular solutions are explained in previous sections. It is clear from Table 1 that comparison
using category of NoSQL isfar much better than comparison using real examples.
Following properties need to be considered for selecting NoSQLsolutions based on specific
requirements:
1.Data model
2.Schema
3.Distributed storage
4.Query response time
5.Query API

Scalability is important parameter to analyze the processing for large scale of data [14][15]. It is
explained in [16] that Big Data frameworks can retain scalability.Scalability in this comparison is not
only for read but also for write, as many research works have concluded that write requires more
replication storage [17]. Read- ers can also decide by the use of Table 1 that which schema and format
requirement is most suitable for application. Advantages ofcategories are also described. There are 120
solutions for NoSql databases [18]. It is very difficult to compare with real solutions.
NoSQL Query Language

The analysis of query model is very important for any data storage [19]. SQL (Structured Query
Language) is the standard used by relational database vendors but, there is no standard query lan- guage
articulated for NoSQL databases. This can be assumed as disadvantage of this storage technique. UnQL
query language is developed to work same as SQL interface, but it is not popularly used till now. Many
NoSQL database use its own query language that is not applicable for other types of database. CQL
(Cassandra Query Language) for Cassandra, Cypher for Neo4J, MongoDB query language, Javascript
for CouchDB are some of examples. It is active research area to define and develop NoSQL databases
standard query language. The difficulty in developing standard query language for NoSQL is that every
solution is designed for specific purpose and use different formats and schema..Category based standard
language is designed by researchers as same cate- gory use same format and schema generally. SPARQL
is standard query designed for many graph databases. Command line interface is used in NoSQL and
NewSQL data stores [8].

For example, MongoDB query structure is same as Sql[20]. Mon- goDB query language has find() method
which works same as select in SQL. db.collection.find() is used to extract some value from database. In
this method, argument is used which works similar as where in SQL.
db.<collection>.find( {title= “document_name”})

Documents are inserted in the collection by the use of following query:


db.<collection>.insert(<document>) ordb.<collection>.save(<document>)

Updation in database use following query: db.<collection>.update(<criteria>)

Following query is used for deletion of document:db.<collection>.remove(<criteria>)

It does not provide foreign key, rather DBRef is used to refer doc- uments in collection.

Features which are supported by MongoDB query language are asfollows:


1.Comparators (<,>,<=,>=)
2.Logical operators
3.Group By
4. Conditional Operators
5. Queries over documents and subdocuments

Cypher is used to query important information from graph data- base. It is declarative language and can
extract information from database without altering graph structure. It is used to extract the relationships
amongst nodes and not on actual structure of nodes. In this language, aggregate functions like max, min,
sum andcount are same as SQL.

Conclusion

In this , techniques for Big data storage are highlighted. Sev- eral techniques and solutions are available
for efficient storage of structured, semi-structured and unstructured data. Distributed data storage,
NewSQL and NoSQL are most commonly used technique identified in this paper. Applications of these
techniques are elabo- rated with advantages and disadvantages. NoSQL data storage technique is the most
popular amongst these solutions. Categories of NoSQL data storage- Column oriented, Graph based, Key
value based and document based are explained in detail with real exam- ples. In this paper, these categories
are compared based on several parameters. Requirement specific solutions are provided for guid- ance of
reader to select most suitable technique. It is explained that query language is not standardized for NoSQL
databases due to different protocols and schema used by four categories. Query languages are briefed for
some solutions. In future, these standard query languages can be further researched and developed by read-
ers. Moreover, extra parameters can be added to compare the NoSQL databases based on architecture.
EX.NO:13 DATABASE CONNECTIVITY USING MYSQL AND PYTHON FOR
HOTEL MANAGEMENT SYSTEM
Date:

AIM:
To implement database connectivity using mysql and python for Hotel
management system

QUERIES:

Mysql commands

create database hotel;

use hotel;
create table custdata(custname varchar(20),addr varchar (30),indate varchar(10),outdate
varchar(10));

create table roomtype (sno varchar(5),roomtype varchar(10),rent integer(10));

insert into roomtype values ('1','type A',1000);

insert into roomtype values ('2','type B',2000);

insert into roomtype values ('3','type C',3000);

insert into roomtype values ('4','type D',4000);

create table restaurent (sno integer(10),itemname varchar(10),rate integer(10));

insert into restaurent values(1,"tea",10);

insert into restaurent values(2,"coffee",10);

insert into restaurent values(3,"colddrink",20);

insert into restaurent values(4,"samosa",10);

insert into restaurent values(5,"sandwich",50);

insert into restaurent values(6,"Dhokla",30);

insert into restaurent values(7,"kachori",10);

insert into restaurent values(8,"milk",20);

insert into restaurent values(9,"noodles",50);

insert into restaurent values(10,"pasta",50);

create table laundary(sno integer(10),itemname varchar(10),rate integer(10));

insert into laundary values(1,"pant",10);

insert into laundary values(2,"shirt",10);

insert into laundary values(3,"suit",10);

insert into laundary values(4,"sari",10);


PYTHON CODE :

import os
import platform
import mysql.connector
import pandas as pd
import datetime
global z
mydb = mysql.connector.connect(user='root',
password='abha',host='localhost',
database='hotel')
mycursor=mydb.cursor()

def registercust():
L=[]
name=input("enter name:")
L.append(name)
addr=input("enter address:")
L.append(addr)
indate=input("enter check in date:")
L.append(indate)
outdate=input("enter check out date:")
L.append(outdate)
cust=(L)
sql="insert into custdata(name,addr,indate,outdate)values(%s,%s,%s,%s)"
mycursor.execute(sql,cust)
mydb.commit()
def roomtypeview():
print("Do yoy want to see room type available : Enter 1 for yes :")
ch=int(input("enter your choice:"))
if ch==1:
sql="select * from roomtype"
mycursor.execute(sql)
rows=mycursor.fetchall()
for x in rows:
print(x)
def roomrent():
print ("We have the following rooms for you:-")
print ("1. type A--- >rs 1000 PN\-")
print ("2. type B--- >rs 2000 PN\-")
print ("3. type C--- >rs 3000 PN\-")
print ("4. type D--- >rs 4000 PN\-")
x=int(input("Enter Your Choice Please->"))
n=int(input("For How Many Nights Did You Stay:"))
if(x==1):
print ("you have opted room type A")
s=1000*n
elif (x==2):
print ("you have opted room type B")
s=2000*n
elif (x==3):
print ("you have opted room type C")
s=3000*n
elif (x==4):
print ("you have opted room type D")
s=4000*n
else:
print ("please choose a room")
print ("your room rent is =",s,"\n")
def restaurentmenuview():
print("Do yoy want to see mebu available : Enter 1 for yes :")
ch=int(input("enter your choice:"))
if ch==1:
sql="select * from restaurent"
mycursor.execute(sql)
rows=mycursor.fetchall()
for x in rows:
print(x)

def orderitem():
global s
print("Do yoy want to see mebu available : Enter 1 for yes :")
ch=int(input("enter your choice:"))
if ch==1:
sql="select * from restaurent"
mycursor.execute(sql)
rows=mycursor.fetchall()
for x in rows:
print(x)

print("do you want to purchase from above list:enter your choice:")


d=int(input("enter your choice:"))
if(d==1):
print("you have ordered tea")
a=int(input("enter quantity"))
s=10*a
print("your amount for tea is :",s,"\n")elif
(d==2):
print("you have ordered coffee")
a=int(input("enter quantity"))
s=10*a
print("your amount for coffee is :",s,"\n")
elif(d==3):
print("you have ordered colddrink")
a=int(input("enter quantity"))
s=20*a
print("your amount for colddrink is :",s,"\n")
elif(d==4):
print("you have ordered samosa")
a=int(input("enter quantity"))
s=10*a
print("your amount fopr samosa is :",s,"\n")
elif(d==5):
print("you have ordered sandwich")
a=int(input("enter quantity"))
s=50*a
print("your amount fopr sandwich is :",s,"\n")
elif(d==6):
print("you have ordered dhokla")
a=int(input("enter quantity"))
s=30*a
print("your amount for dhokla is :",s,"\n")
elif(d==7):
print("you have ordered kachori")
a=int(input("enter quantity"))
s=10*a
print("your amount for kachori is :",s,"\n")
elif(d==8):
print("you have ordered milk")
a=int(input("enter quantity"))
s=20*a
print("your amount for kachori is :",s,"\n")
elif(d==9):
print("you have ordered noodles")
a=int(input("enter quantity"))
s=50*a
print("your amount for noodles is :",s,"\n")
elif(d==10):
print("you have ordered pasta")
a=int(input("enter quantity"))
s=50*a
print("your amount for pasta is :",s,"\n")
else:
Print("please enter your choice from the menu")
def laundarybill():
global z
print("Do yoy want to see rate for laundary : Enter 1 for yes :")
ch=int(input("enter your choice:"))
if ch==1:
sql="select * from laundary"
mycursor.execute(sql)
rows=mycursor.fetchall()
for x in rows:
print(x)
y=int(input("Enter Your number of clothes->"))
z=y*10
print("your laundary bill:",z,"\n")
return z
def lb():
print(z)
def res():
print(s)
def viewbill():
a=input("enter customer name:")
print("customer name :",a,"\n")
print("laundarey bill:")
print(lb) print("restaurent
bill:")print(res)

def Menuset():
print("enter 1: To enter customer data")
print("enter 2 : To view roomtype") print("enter
3 : for calculating room bill") print("enter 4 : for
viewing restaurent menu")print("enter 5 : for
restaurent bill") print("enter 6 :for laundary bill")
print("enter 7 : for complete bill")
print("enter 8 : for exit:")
try:
userinput=int(input("pleaseselect an above option:"))
except ValueError:
exit("\n hi thats not a number")

userinput=int(input("enter your choice"))


if(userinput==1):
registercust()
elif(userinput==2):
roomtypeview()
elif(userinput==3):
roomrent()
elif(userinput==4):
restaurentmenuview()
elif(userinput==5):
orderitem()
elif(userinput==6):
laundarybill()
elif(userinput==7):
viewbill()
elif(userinput==8):
quit()
else:
print("enter correct choice")
Menuset()
def runagain():
runagn=input("\n want to run again y/n:")
while(runagn.lower()=='y'):
if(platform.system()=="windows"):
print(os.system('cls'))
else:
print(os.system('clear'))Menuset()
runagn=input("\n want to run again y/n:")
runagain()
OUTPUT
RESULT:

Thus the implemention of database connectivity using mysql and python for Hotel management system has
been created and executed successfully.
EX.NO:14 Library Management System using MYSQL
Date:

AIM:
To implement Library Management System using MYSQL

Analysis of Features:

 Record while issuing books- When anyone takes a book, staff should be able to scan the barcode on the book
and should be able to enter the record.
 Profile editing- Staff should be able to edit the profile and the profiles of the people with membership in that
library.
 They should be able to keep track of books issued by them.
 Should be able to ask, request, or demand the books from the people who took that if they crossed the due date.
 They should be able to track books, their place, and so on.
 If there occurs any change in the system, or if anyone else entered details or tried to access the system, staff
should get the notification.

QUERIES:

Creating Tables

So our first step is to create tables. Let us create a database as db_LibraryManagement and then create
all the required tables inside it.

CREATE PROC dbo.LibraryManagementSystemProcedure


AS CREATE DATABASE db_LibraryManagement
GO
CREATE TABLE table_publisher (
PublisherName VARCHAR(50) PRIMARY KEY NOT NULL,
PublisherAddress VARCHAR(100) NOT NULL,
PublisherPhone VARCHAR(20) NOT NULL,
);

Now let’s create a table for a book.

CREATE TABLE table_book (


BookID INT PRIMARY KEY NOT NULL IDENTITY (1,1),
Book_Title VARCHAR(100) NOT NULL,
PublisherName VARCHAR(100) NOT NULL
);

Similarly, create a table for the library branch.

CREATE TABLE table_library_branch (


library_branch_BranchID INT PRIMARY KEY NOT NULL IDENTITY (
library branch BranchName VARCHAR(100) NOT NULL, library_branch_BranchAddress VARCHAR(200) NOT
NULL,
);

View the library branch table.

SELECT FROM table_library_branch


CREATE TABLE table_borrower (
CardNo INT PRIMARY KEY NOT NULL IDENTITY (100,1),
BorrowerName VARCHAR(100) NOT NULL,
BorrowerAddress VARCHAR(200) NOT NULL,
BorrowerPhone VARCHAR(50) NOT MILL,
);

Create a table to store the book copies.

CREATE TABLE table_book_copies (


book_copies CopiesID INT PRIMARY KEY NOT NULL
book_copies BookID INT NOT NULL
book_copies BranchID INT NOT NULL
book_copies No Of Copies INT NOT NULL,
);

Create one more table for storing book authors


SELECT FROM table_book_copies CREATE TABLE table_book_authors (
book_authors AuthorID INT PRIMARY KEY NOT NULL IDENTITY (1,1),
book_authors BookID INT NOT NULL CONSTRAINT fk_book_id3 FOREIGN KEY REFERENCES
table_book(book_BookID) ON UPDATE CASCADE ON DELETE CASCADE, table_book(book_BookID) ON
UPDATE CASCADE,
book authors AuthorName VARCHAR(50) NOT NULL,
);
SELECT FROM table_book_authors

Inserting Data

Next is having some data inserted into the tables.

-- Table structure for table `book`

CREATE TABLE IF NOT EXISTS `book` (

`isbn` char(13) NOT NULL,

`title` varchar(80) NOT NULL,

`author` varchar(80) NOT NULL,

`category` varchar(80) NOT NULL,

`price` int(4) unsigned NOT NULL,

`copies` int(10) unsigned NOT NULL

);
Adding data into the table book.

INSERT INTO `book` (`isbn`, `title`, `author`, `category`, `price`, `copies`) VALUES

('9788654552277', 'X-Men: God Loves, Man Kills', 'Chris', 'Comics', 98, 39),

('0964161484100', 'Mike Tyson : Undisputed Truth', 'Larry Sloman, Mike Tyson', 'Sports', 654, 79),

('6901142585540', 'V for Vendetta', 'Alan Moore', 'Comics', 600, 23),

('9094996245442', 'When Breath Becomes Air', 'Paul Kalanithi', 'Medical', 500, 94),

('8653491200700', 'The Great Gatsby', 'F. Scott Fitzgerald', 'Fiction', 432, 120);

Structure of the table for book issue.

CREATE TABLE IF NOT EXISTS `book_issue` (

`issue_id` int(11) NOT NULL,

`member` varchar(20) NOT NULL,

`book_isbn` varchar(13) NOT NULL,

`due_date` date NOT NULL,

`last_reminded` date DEFAULT NULL

);
CREATE TRIGGER `issue_book` BEFORE INSERT ON `book_issue`
FOR EACH ROW BEGIN

SET NEW.due_date = DATE_ADD(CURRENT_DATE, INTERVAL 20 DAY);

UPDATE member SET balance = balance - (SELECT price FROM book WHERE

isbn = NEW.book_isbn) WHERE username = NEW.member;

UPDATE book SET copies = copies - 1 WHERE isbn = NEW.book_isbn;

DELETE FROM pending_book_requests WHERE member = NEW.member AND book_isbn = NEW.book_isbn;

END
CREATE TRIGGER `return_book` BEFORE DELETE ON `book_issue`

FOR EACH ROW BEGIN

UPDATE member SET balance = balance + (SELECT price FROM book WHERE isbn = OLD.book_isbn)
WHERE username = OLD.member;

UPDATE book SET copies = copies + 1 WHERE isbn = OLD.book_isbn;

END

Structure of librarian table.

CREATE TABLE IF NOT EXISTS `librarian` (

`id` int(11) NOT NULL,

`username` varchar(20) NOT NULL,


`password` char(40) NOT NULL

);

Adding details of the librarian.

INSERT INTO `librarian` (`id`, `username`, `password`) VALUES

(1, 'Vani', 'xthds97@3h$yfc*jrk0%dfg$');

Structure of table for the member.

CREATE TABLE IF NOT EXISTS `member` (

`id` int(11) NOT NULL,

`username` varchar(20) NOT NULL,

`password` char(40) NOT NULL,

`name` varchar(80) NOT NULL,

`email` varchar(80) NOT NULL,

`balance` int(4) NOT NULL

);
CREATE TRIGGER `add_member` AFTER INSERT ON `member`

FOR EACH ROW DELETE FROM pending_registrations WHERE username = NEW.username


CREATE TRIGGER `remove_member` AFTER DELETE ON `member`

FOR EACH ROW DELETE FROM pending_book_requests WHERE member = OLD.username

Structure of table for pending book requests


CREATE TABLE IF NOT EXISTS `pending_book_requests` (

`request_id` int(11) NOT NULL,

`member` varchar(20) NOT NULL,

`book_isbn` varchar(13) NOT NULL,

`time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP

);

Structure of table for pending registrations.

CREATE TABLE IF NOT EXISTS `pending_registrations` (

`username` varchar(30) NOT NULL,

`password` char(20) NOT NULL,

`name` varchar(40) NOT NULL,

`email` varchar(20) NOT NULL,

`balance` int(10),
`time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP

);

Add data for pending registrations table.

INSERT INTO `pending_registrations`

(`username`, `password`, `name`, `email`, `balance`, `time`)

VALUES

('Robin200', '7t6hg$56y^', 'Robin', '[email protected]', 200, '2021-03-21 08:59:00'),

('Aadhya100', 'Ujgf(76G5$#f@df', 'Aadhya', '[email protected]', 1500, '2021-03-21 2:14:53');

Now let’s add primary keys to these tables.

ALTER TABLE `book`

ADD PRIMARY KEY (`isbn`);

ALTER TABLE `book_issue`

ADD PRIMARY KEY (`issue_id`);

ALTER TABLE `librarian`

ADD PRIMARY KEY (`id`), ADD UNIQUE KEY `username` (`username`);


ALTER TABLE `member`

ADD PRIMARY KEY (`id`), ADD UNIQUE KEY `username` (`username`), ADD UNIQUE KEY `email` (`email`);

ALTER TABLE `pending_book_requests`

ADD PRIMARY KEY (`request_id`);

ALTER TABLE `pending_registrations`

ADD PRIMARY KEY (`username`);

Testing

The below code is to test whether we are getting the correct output. We are getting to know the number
of books named The Lost Tribe present in the library Sharpstown.

CREATE PROC dbo.bookCopiesAtAllSharpstown


AS
SELECT copies.book_copies_BranchID AS [Branch ID], branch.library_branch_BranchName AS [Branch Name],
copies.book_copies_No_Of_Copies AS [Number of Copies],
book.book_Title AS [Book Title]
FROM table_book_copies AS copies
INNER JOIN table_book AS book ON copies.book_copies_BookID =
book.book_BookID
INNER JOIN table_library_branch AS branch ON book_copies_BranchID =
branch.library_branch_BranchID
WHERE book.book_Title = @bookTitle AND branch.library_branch_BranchName = @branchName
GO
EXEC dbo.bookCopiesAtAllSharpstown
(@bookTitle varchar(70) = 'The Lost Tribe', @branchName varchar(70) = 'Sharpstown')

You might also like