Final Dbms Lab Manual
Final Dbms Lab Manual
21HC39P
LAB MANUAL
Prepared by,
B.Sumathi & V.Tamilsevi
Assistant Professor/IT
1. Data Definition Commands, Data Manipulation Commands for
Joins.
3. Creating an employee database to set various constraints and
AIM:
To create table and execute data definition commands.
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>;
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
Syntax:
ALTER TABLE table_name ADD (column_name datatype);
Syntax
ALTER TABLE table_name ADD( column_name1 datatype1, column-name2 datatype2,.. );
Syntax
Syntax
Syntax
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
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
RENAME query
RENAME command is used to set a new name for any existing table.
Syntax
DROP TABLE
QUERIES
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.
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.
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.
Q6: Truncate the emp table and drop the dept table
Solution:
1. Use the drop, truncate table syntax to drop and truncate the table.
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;
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;
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:
1 Mathi AP 1 10000
2 Arjun ASP 2 12000
3 Gugan ASP 1 12000
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:
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
Solution:
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.
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
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:
PNR_No
10201
10202
10203
10204
Q2:Display the ticket numbers and names of all the passengers.
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.
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:
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.
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:
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:
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:
Example:
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.
Syntax:
[CONSTRAINT constraint_name]
FOREIGN KEY [foreign_key_name] (col_name, ...)
REFERENCES parent_tbl_name (col_name,...)
ON DELETE referenceOption
ON UPDATE referenceOption
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
Table: contact
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)
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:
Example:
CREATE TABLE Persons1 (
ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int,
City varchar(255) DEFAULT 'Sandnes'
);
QUERIES
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.
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)
mysql> CREATE TABLE Employe(Id INTEGER, Name TEXT NOT NULL, Hometown VARCHAR(40));
Query OK, 0 rows affected (0.17 sec)
2. ‘UNIQUE’ Constraint
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)
AIM:
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
SELECT columns
FROM tables
[WHERE conditions];
Q1: Create a name for view for the ‘courses’ table in databases.
In MYSQL, the ALTER VIEW statement is used to modify or update the already created VIEW without
dropping it.
Syntax:
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
Q3: Drop the existing VIEW by using the DROP VIEW statement.
Q4: The organization wants to display only the details of the employees those who are ASP.
Solution:
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
Example
Q9:create an index for the jobTitle column by using the CREATE INDEX statement.
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 .
AIM:
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
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.
INSERT,
UPDATE and
DELETE
%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.
AIM:
MYSQL HANDLER:
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
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:
Q1:Insert a duplicate value into EmpID column to check the continue handler SQL exception
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;
AIM:
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 ;
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.
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 //
BEGIN
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 ;
Q4:Create a procedure that takes an initial value of the counter and increment it with a given number.
DELIMITER //
BEGIN
END //
DELIMITER ;
Q5:write a procedure to take studentId and depending on the studentMarks we need to return the class
according to the below criteria.
DELIMITER $$
BEGIN
ELSE
END$$
DELIMITER ;
In MySQL, a function is a stored program that you can pass parameters into and then return a value.
This reference contains string, numeric, date, and some advanced functions in MySQL.
Syntax
DELIMITER $$
parameter1,
parameter2,…
RETURNS datatype
[NOT] DETERMINISTIC
BEGIN
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 ;
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:
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).
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.
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:
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.
BEGIN
--variable declarations
--trigger code
END;
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 //
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 $$;
END$$
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.
AIM:
CREATION OF DATABASE
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.
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
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:
AIM:
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 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.
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 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
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
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.
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.
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”})
It does not provide foreign key, rather DBRef is used to refer doc- uments in collection.
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
use hotel;
create table custdata(custname varchar(20),addr varchar (30),indate varchar(10),outdate
varchar(10));
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)
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")
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.
Inserting Data
);
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),
('9094996245442', 'When Breath Becomes Air', 'Paul Kalanithi', 'Medical', 500, 94),
('8653491200700', 'The Great Gatsby', 'F. Scott Fitzgerald', 'Fiction', 432, 120);
);
CREATE TRIGGER `issue_book` BEFORE INSERT ON `book_issue`
FOR EACH ROW BEGIN
UPDATE member SET balance = balance - (SELECT price FROM book WHERE
END
CREATE TRIGGER `return_book` BEFORE DELETE ON `book_issue`
UPDATE member SET balance = balance + (SELECT price FROM book WHERE isbn = OLD.book_isbn)
WHERE username = OLD.member;
END
);
);
CREATE TRIGGER `add_member` AFTER INSERT ON `member`
);
`balance` int(10),
`time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP
);
VALUES
ADD PRIMARY KEY (`id`), ADD UNIQUE KEY `username` (`username`), ADD UNIQUE KEY `email` (`email`);
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.