Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Dbms Lab Manual1

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 47

EX NO: 1

DDL & DML COMMANDS


DATE:

AIM:
To create a database table, add constraints (primary key, unique, check, Not null), insert rows, update and
delete rows using SQL DDL and DML commands.

NOT NULL Constraint in SQL

By default, the columns are able to hold NULL values. A NOT NULL constraint in SQL is used to prevent
inserting NULL values into the specified column, considering it as a not accepted value for that column. This
means that you should provide a valid SQL NOT NULL value to that column in the INSERT or UPDATE
statements, as the column will always contain data.

UNIQUE Constraints in SQL

The UNIQUE constraint in SQL is used to ensure that no duplicate values will be inserted into a specific
column or combination of columns that are participating in the UNIQUE constraint and not part of the
PRIMARY KEY. In other words, the index that is automatically created when you define a UNIQUE
constraint will guarantee that no two rows in that table can have the same value for the columns participating
in that index, with the ability to insert only one unique NULL value to these columns, if the column allows
NULL.
SQL PRIMARY KEY Constraint

The PRIMARY KEY constraint consists of one column or multiple columns with values that uniquely identify
each row in the table.

The SQL PRIMARY KEY constraint combines between the UNIQUE and SQL NOT NULL constraints,
where the column or set of columns that are participating in the PRIMARY KEY cannot accept a NULL
value. If the PRIMARY KEY is defined in multiple columns, you can insert duplicate values on each column
individually, but the combination values of all PRIMARY KEY columns must be unique. Take into
consideration that you can define only one PRIMARY KEY per each table, and it is recommended to use
small or INT columns in the PRIMARY KEY.
CHECK Constraint

A CHECK constraint is defined on a column or set of columns to limit the range of values, that can be inserted
into these columns, using a predefined condition. The CHECK constraint comes into action to evaluate the
inserted or modified values, where the value that satisfies the condition will be inserted into the table,
otherwise, the insert operation will be discarded. It is allowed to specify multiple CHECK constraints for the
same column.

Web reference : https://www.sqlshack.com/commonly-used-sql-server-constraints-not-null-unique-primary-


key/

https://www.mariadbtutorial.com/getting-started/

DEFAULT Constraint

A DEFAULT constraint is used to provide a default column value for the inserted rows if no value is specified
for that column in the INSERT statement. The Default constraint helps in maintaining the domain integrity by
providing proper values for the column, in case the user does not provide a value for it. The default value can
be a constant value, a system function value or NULL.
Insert command in SQL

The insert statement allows you to add a new row to a table. The following shows the syntax of the insert
statement:

insert into table_name(column_list) values(value_list);

MariaDB provides an alternative syntax for inserting a new row into a table using the set clause:

insert into table_name set column1 = value1, column2 = value2, ...;

UPDATE Statement

The UPDATE is used to update the values of one or multiple columns of a table. The syntax is the following:
UPDATE tablename
SET
col_name1 = NewValue_1,
col_name2 = NewValue_2,
col_name3 = NewValue_3,
...
WHERE
condition;

INFERENCE:

RESULT:

EX NO: 2
DATE: REFERENTIAL INTEGRITY CONSTRAINTS

AIM:

To create a set of tables, add foreign key constraints and incorporate referential integrity.

Foreign Key

A foreign key relationship involves a parent table that holds the initial column values, and a child table with
column values that reference the parent column values. A foreign key constraint is defined on the child table.

This following example relates parent and child tables through a single-column foreign key and shows how a
foreign key constraint enforces referential integrity.

Create the parent and child tables:


INFERENCE:

RESULT:

EX NO: 3
DATE: AGGREGATE FUNCTIONS

AIM:

To query the database tables using different ‘where’ clause conditions and also implement aggregate
functions.
SYNTAX:

create table dept(deptno int(2) primary key, dname varchar(10),loc varchar(10));

create table emp1(ename varchar(10),empno int check(empno>50));

Create table Emp ( EmpNo int(5), EName VarChar(15), Job Char(10) unique, DeptNo int(3),sal float(7,2),
foreign key(DeptNo) REFERENCES dept(deptno));

insert into dept values (1,'IT','Salem’);

insert into emp values(1.,'Mathi','AP',1,10000.00);

insert into dept values (2,'CSE','Trichy');

insert into emp values(2.,'Arjun','ASP',2,12000.00);


insert into dept values (3,'CSBS','Chennai');

insert into emp values(30,'Gugan','PROF',3,15000.00);

insert into emp values(35,'Vijayan','PRO',3,45000.00);

‘order by’ clause

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

select * from emp order by sal;

List the records in the emp table orderby salary in descending order.

select * from emp order by sal desc;

Display deptno from the table employee avoiding the duplicated values.

select distinct deptno from emp;

select deptno from emp;


CHARACTER/STRING FUNCTION:

select upper('welcome') from dual;

select lower('HAI') from dual;

select ltrim(' hai') from dual;

select rtrim('hai ')from dual;

select concat('CIT',' Autonomous')from dual;

select length('CIT')from dual;

select replace('Anna university', 'Anna','CIT')from dual;

select substr('Institution', 6,6)from dual;

select rpad('hai',3,'*')from dual;


select lpad('hai',7,'#*')from dual;

select replace('Dany','y','iel')from dual;

NUMERIC FUNCTION

SQL> select round(15.6789)from dual;

ROUND(15.6789)

--------------

16

SQL> select ceil(23.20)from dual;

CEIL(23.20)

-----------

24

SQL> select floor(34.56)from dual;

FLOOR(34.56)

------------

34

SQL> select trunc(15.56743)from dual;

TRUNC(15.56743)

---------------

15

SQL> select sign(-345)from dual;

SIGN(-345)

----------

-1
SQL> select abs(-70)from dual;

ABS(-70)

---------

70

MATH FUNCTION:

SQL> select abs(45) from dual;

ABS(45)

---------

45

SQL> select power(10,12) from dual;

POWER(10,12)

------------

1.000E+12

SQL> select mod(11,5) from dual;

MOD(11,5)

---------

SQL> select exp(10) from dual;

EXP(10)

---------

22026.466

SQL> select sqrt(225) from dual;

SQRT(225)

---------

15
The SQL COUNT(), AVG() and SUM() Functions
The COUNT() function returns the number of rows that matches a specified criterion.

COUNT() Syntax
SELECT COUNT(column_name)
FROM table_name
WHERE condition;

The AVG() function returns the average value of a numeric column.

AVG() Syntax
SELECT AVG(column_name)
FROM table_name
WHERE condition;

The SUM() function returns the total sum of a numeric column.

SUM() Syntax
SELECT SUM(column_name)
FROM table_name
WHERE condition;

The SQL MIN() and MAX() Functions


The MIN() function returns the smallest value of the selected column.

The MAX() function returns the largest value of the selected column.

MIN() Syntax
SELECT MIN(column_name)
FROM table_name
WHERE condition;

MAX() Syntax
SELECT MAX(column_name)

FROM table_name
WHERE condition;

INFERENCE:
RESULT:
EX NO: 4
SUB QUERIES AND JOIN OPERATIONS
DATE:

AIM:

To uery the database tables and explore sub queries and simple join operations.
SYNTAX:

SUB QUERIES:

SALESMAN TABLE
salesman_id name city commission

----------- ---------- ---------- ----------


5001 James Hoog New York 0.15
5002 Nail Knite Paris 0.13
5005 Pit Alex London 0.11
5006 Mc Lyon Paris 0.14
5003 Lauson Hen San Jose 0.12
5007 Paul Adam Rome 0.13

ORDERS TABLE

ord_no purch_amt ord_date customer_id salesman_id


---------- ---------- ---------- ----------- -----------
70001 150.5 2012-10-05 3005 5002
70009 270.65 2012-09-10 3001 5005
70002 65.26 2012-10-05 3002 5001
70004 110.5 2012-08-17 3009 5003
70007 948.5 2012-09-10 3005 5002
70005 2400.6 2012-07-27 3007 5001
70008 5760 2012-09-10 3002 5001
70010 1983.43 2012-10-10 3004 5006
70003 2480.4 2012-10-10 3009 5003
70012 250.45 2012-06-27 3008 5002
70011 75.29 2012-08-17 3003 5007
70013 3045.6 2012-04-25 3002 5001

CUSTOMER TABLE

customer_id cust_name city grade salesman_id


----------- ------------ ---------- ---------- -----------
3002 Nick Rimando New York 100 5001
3005 Graham Zusi California 200 5002
3001 Brad Guzan London 5005
3004 Fabian Johns Paris 300 5006
3007 Brad Davis New York 200 5001
3009 Geoff Camero Berlin 100 5003
3008 Julian Green London 300 5002
3003 Jozy Altidor Moscow 200 5007
EX NO: 5
NATURAL, EQUI AND OUTER JOINS
DATE: 1.Write a qu
ery to displa
y all the orders from the orders table issued by the salesman 'paul adam'.
mysql>SELECT * FROM orders WHERE salesman_id = (select salesman_id FROM salesman

WHEREname='Paul Adam');

2.Write a query to display all the orders which values are greater than the average order value for
10th October 2012.
mysql>SELECT * FROM orders WHERE purch_amt > (select AVG(purch_amt) FROM orders

whereord_date ='10/10/2012');
3. Write a query to find the sums of the amounts from the orders table, grouped by date, eliminating
all those dates where the sum was not at least 1000.00 above the maximum amount for that date.
mysql>SELECT ord_date, SUM (purch_amt) FROM orders a GROUP BY ord_date HAVING SUM

(purch_amt) > (SELECT 1000.00 + MAX(purch_amt) FROM orders b WHERE a.ord_date =


b.ord_date);

4. Write a query to extract the data from the customer table if and only if one or more of the
customers in the customer table are located in London.
mysql>SELECT customer_id,cust_name, city FROM customer WHERE EXISTS (SELECT * FROM

customer WHERE city='London');

5.Write a query to find all the salesmen who worked for only one customer.
mysql>SELECT * FROM salesman WHERE salesman_id IN (SELECT DISTINCT salesman_id FROM

customer a WHERE NOT EXISTS (SELECT * FROM customer b WHERE a.salesman_id =


b.salesmanidAND a.cust_name<>b.cust_name));

6.Write a query to find all those customers who hold a different grade than any customer of the city
Dallas.
mysql>SELECT *FROM customer WHERE NOT grade = ANY (SELECT grade FROM customerWHERE

city='Dallas');

INFERENCE:

RESULT:
To query the database tables and explore natural, equi and outer joins.

Table: Emp

mysql> create table emp(empno int primary key,ename char(10),job


AIM:
char(5),deptno int,sal int);
Query OK, 0 rows affected (0.00 sec)

mysql> desc emp;


+--------+----------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+--------+----------+------+-----+---------+-------+
| empno | int(11) | NO | PRI | NULL | |
| ename | char(10) | YES | | NULL | |
| job | char(5) | YES | | NULL | |
| deptno | int(11) | YES | | NULL | |
| sal | int(11) | YES | | NULL | |
+--------+----------+------+-----+---------+-------+
5 rows in set (0.00 sec)

Table:Depart
mysql> create table depart(deptno int,dname char(12),loc char(12));

Query OK, 0 rows affected (0.01 sec)

mysql> alter table depart add foreign key(deptno) references emp(deptno);


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

mysql> desc depart;


+--------+----------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+--------+----------+------+-----+---------+-------+
| deptno | int(11) | YES | MUL | NULL | |
| dname | char(12) | YES | | NULL | |
| loc | char(12) | YES | | NULL | |
+--------+----------+------+-----+---------+-------+
3 rows in set (0.00 sec)

Table:Staff
mysql> create table staff(staff_id int primary key,staff_name char(10),expr

int,age int);
Query OK, 0 rows affected (0.00 sec)

mysql> desc staff;


+------------+----------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+------------+----------+------+-----+---------+-------+
| staff_id | int(11) | NO | PRI | NULL | |
| staff_name | char(10) | YES | | NULL | |
| expr | int(11) | YES | | NULL | |
| age | int(11) | YES | | NULL | |
+------------+----------+------+-----+---------+-------+
4 rows in set (0.00 sec)

Table:Book

mysql> create table book(book_id int,book_name char(12),edition int,primary


key(book_id),check(edition in(1,2,3)));
Query OK, 0 rows affected (0.00 sec)

mysql> desc book;


+-----------+----------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-----------+----------+------+-----+---------+-------+
| book_id | int(11) | NO | PRI | 0 | |
| book_name | char(12) | YES | | NULL | |
| edition | int(11) | YES | | NULL | |
+-----------+----------+------+-----+---------+-------+
3 rows in set (0.00 sec)

Table:Issue

mysql> create table issue(staff_id int,book_id int,day date,primary


key(staff_id,book_id));
Query OK, 0 rows affected (0.01 sec)

mysql> alter table issue add foreign key(book_id) references book(book_id);


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

mysql> alter table issue add foreign key(staff_id) references


staff(staff_id);
Query OK, 0 rows affected (0.01 sec)
Records: 0 Duplicates: 0 Warnings: 0

mysql> desc issue;


+----------+---------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+----------+---------+------+-----+---------+-------+
| staff_id | int(11) | NO | PRI | 0 | |
| book_id | int(11) | NO | PRI | 0 | |
| day | date | YES | | NULL | |
+----------+---------+------+-----+---------+-------+
3 rows in set (0.00 sec)
Inserting records in all the created tables:

mysql> insert into emp values(1,'Arjun','AP',1,10000);


Query OK, 1 row affected (0.00 sec)

mysql> insert into emp values(2,'Barath','ASP',2,20000);


Query OK, 1 row affected (0.00 sec)

mysql> insert into emp values(3,'Aparna','ASP',2,20000);


Query OK, 1 row affected (0.00 sec)

mysql> insert into emp values(4,'Karthik','AP',1,10000);


Query OK, 1 row affected (0.00 sec)

mysql> select * from emp;


+-------+---------+------+--------+-------+
| empno | ename | job | deptno | sal |
+-------+---------+------+--------+-------+
| 1 | Arjun | AP | 1 | 10000 |
| 2 | Barath | ASP | 2 | 20000 |
| 3 | Aparna | ASP | 2 | 20000 |
| 4 | Karthik | AP | 1 | 10000 |
+-------+---------+------+--------+-------+
4 rows in set (0.00 sec)
----------------------------------------------------------------------------
mysql> create table depart(deptno int,dname char(12),loc char(12));
Query OK, 0 rows affected (0.01 sec)

mysql> alter table depart add foreign key(deptno) references emp(deptno);


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

mysql> insert into depart values(1,'Accounting','Newyork');


Query OK, 1 row affected (0.00 sec)

mysql> insert into depart values(2,'Research','Dallas');


Query OK, 1 row affected (0.00 sec)

mysql> select * from depart;


+--------+------------+---------+
| deptno | dname | loc |
+--------+------------+---------+
| 1 | Accounting | Newyork |
| 2 | Research | Dallas |
| 30 | Sales | Chicago |
| 40 | Operation | Boston |
+--------+------------+---------+
4 rows in set (0.00 sec)

mysql> insert into staff values(11,'John',8,27);


Query OK, 1 row affected (0.00 sec)

mysql> insert into staff values(12,'Priya',9,29);


Query OK, 1 row affected (0.00 sec)
mysql> select * from staff;

+----------+------------+------+------+
| staff_id | staff_name | expr | age |
+----------+------------+------+------+
| 11 | John | 8| 27 |
| 12 | Priya | 9| 29 |
| 13 | Beulah | 10 | 36 |
+----------+------------+------+------+
3 rows in set (0.00 sec)

mysql> insert into book values(1023,'OOPS',3);


Query OK, 1 row affected (0.00 sec)
mysql> insert into book values(1056,'DBMS',2);
Query OK, 1 row affected (0.00 sec)

mysql> select * from book;


+---------+-----------+---------+
| book_id | book_name | edition |
+---------+-----------+---------+
| 1023 | OOPS | 3|
| 1056 | DBMS | 2|
| 1036 | CN | 1|
+---------+-----------+---------+
3 rows in set (0.00 sec)
----------------------------------------------------------------------------
mysql> insert into issue values(11,1023,'11-aug-14');
Query OK, 1 row affected, 1 warning (0.00 sec)

mysql> insert into issue values(12,1056,'15-dec-14');


Query OK, 1 row affected, 1 warning (0.00 sec)

mysql> select * from issue;


+----------+---------+------------+
| staff_id | book_id | day |
+----------+---------+------------+
| 11 | 1023 | 0000-00-00 |
| 12 | 1056 | 0000-00-00 |
+----------+---------+------------+
2 rows in set (0.00 sec)

JOIN COMMANDS

EQUI-JOIN
Display the employee details, departments that the departments are same in both the emp and dept.

mysql> select * from emp,depart where emp.deptno=depart.deptno;


+-------+---------+------+--------+-------+--------+------------+---------+
| empno | ename | job | deptno | sal | deptno | dname | loc |
+-------+---------+------+--------+-------+--------+------------+---------+
| 1 | Arjun | AP | 1 | 10000 | 1 | Accounting | Newyork |
| 4 | Karthik | AP | 1 | 10000 | 1 | Accounting | Newyork |
| 2 | Barath | ASP | 2 | 20000 | 2 | Research | Dallas |
| 3 | Aparna | ASP | 2 | 20000 | 2 | Research | Dallas |
+-------+---------+------+--------+-------+--------+------------+---------+
4 rows in set (0.00 sec)
NON EQUI-JOIN
Display the employee details, departments that the departments are not same in both the emp and
dept.
mysql> select * from emp,depart where emp.deptno!=depart.deptno;
+-------+---------+------+--------+-------+--------+------------+---------+
| empno | ename | job | deptno | sal | deptno | dname | loc |
+-------+---------+------+--------+-------+--------+------------+---------+
| 2 | Barath | ASP | 2 | 20000 | 1 | Accounting | Newyork |
| 1 | Arjun | AP | 1 | 10000 | 2 | Research | Dallas |
| 4 | Karthik | AP | 1 | 10000 | 2 | Research | Dallas |
+-------+---------+------+--------+-------+--------+------------+---------+
12 rows in set (0.00 sec)

LEFT OUTER JOIN


Display Ename and location using LEFT OUTER JOIN
mysql> select emp.ename,loc from emp left outer join depart on
emp.deptno=depart.deptno;
+---------+---------+
| ename | loc |
+---------+---------+
| Arjun | Newyork |
| Barath | Dallas |
| Aparna | Dallas |
| Karthik | Newyork |
+---------+---------+
4 rows in set (0.00 sec)

RIGHT OUTER JOIN


Write a Query to display Ename,Job and Sal using Right outer Join
mysql> select emp.ename,job,sal from emp right outer join depart on
depart.deptno=emp.deptno;
+---------+------+-------+
| ename | job | sal |
+---------+------+-------+
| Arjun | AP | 10000 |
| Barath | ASP | 20000 |
| Aparna | ASP | 20000 |
| NULL | NULL | NULL |
| NULL | NULL | NULL |
+---------+------+-------+
6 rows in set (0.00 sec)

SELF JOIN
Write a Query to display employee names using Self Join
mysql> select distinct ename from emp x,depart y where x.deptno=y.deptno;
+---------+
| ename |
+---------+
| Arjun |
| Barath |
| Aparna |
+---------+
4 rows in set (0.00 sec)
SUB-QUERY (query within another query)
Update deptno by adding empno and keep that as deptno for employee 4.
mysql> update emp set deptno=( select sum(empno)from depart) where empno=4;
Query OK, 1 row affected (0.00 sec)
Rows matched: 1 Changed: 1 Warnings: 0

mysql> select * from emp;


+-------+---------+------+--------+-------+
| empno | ename | job | deptno | sal |
+-------+---------+------+--------+-------+
| 1 | Arjun | AP | 1 | 10000 |
| 2 | Barath | ASP | 2 | 20000 |
EX NO: 6
FUNCTIONS AND STORED PROCEDURES
DATE:
|
3 | Aparna | ASP | 2 | 20000 |
+-------+---------+------+--------+-------+
4 rows in set (0.00 sec)

Display staff name who has the bookid 1023.


AIM:
mysql> select staff_name from staff where staff_id in(select staff_id from
issue where book_id=1023);
+------------+
| staff_name |
+------------+
| John |
+------------+
1 row in set (0.00 sec)

Display staff_id whose edition is 2.


mysql> select staff_id from issue where book_id in(select book_id from book
where edition=2);
+----------+

| staff_id |
+----------+
| 12 |
+----------+
1 row in set (0.00 sec)

INFERENCE:

RESULT:

To implement procedure and functions.

SYNTAX

CREATE
[DEFINER = { user | CURRENT_USER }]
PROCEDURE sp_name ([proc_parameter[,...]])
[characteristic ...] routine_body

CREATE
[DEFINER = { user | CURRENT_USER }]
FUNCTION sp_name ([func_parameter[,...]])
RETURNS type
[characteristic ...] routine_body
proc_parameter:
[ IN | OUT | INOUT ] param_name type
func_parameter:
param_name type
type:
Any valid MySQL data type
characteristic:
LANGUAGE SQL
| [NOT] DETERMINISTIC
| { CONTAINS SQL | NO SQL | READS SQL DATA | MODIFIES SQL DATA }
| SQL SECURITY { DEFINER | INVOKER }
| COMMENT 'string'

routine_body:
Valid SQL procedure statement

FUNTION SYNTAX:

CREATE
[DEFINER = { user | CURRENT_USER }]
FUNCTION sp_name ([func_parameter[,...]])
RETURNS type
[characteristic ...] routine_body

func_parameter:
param_name type
FACTORIAL OF GIVEN NUMBER

mysql> delimiter $$
mysql> CREATE PROCEDURE factorial(IN x INT)
-> BEGIN
-> DECLARE result INT;
-> DECLARE i INT;
-> SET result = 1;
-> SET i = 1;
-> WHILE i <= x DO
-> SET result = result * i;
-> SET i = i + 1;
-> END WHILE;
-> SELECT x AS Number, result as Factorial;
-> END;
-> $$
Query OK, 0 rows affected (0.00 sec)
mysql> call factorial(5)
-> $$
+--------+-----------+
| Number | Factorial |
+--------+-----------+
| 5 | 120 |
+--------+-----------+
1 row in set (0.00 sec)
Query OK, 0 rows affected (0.00 sec)

Procedure to get input from user

mysql> select * from depart;


+--------+------------+---------+
| deptno | dname | loc |
+--------+------------+---------+
| 1 | Accounting | Newyork |
| 2 | Research | Dallas |
| 30 | Sales | Chicago |
+--------+------------+---------+
4 rows in set (0.00 sec)
mysql> delimiter //
mysql> create procedure getin(IN loca varchar(12))
-> BEGIN
-> Select * from depart where loc=loca;
-> END //
Query OK, 0 rows affected (0.00 sec)

mysql> delimiter ;
mysql> CALL getin('Boston');
+--------+-----------+--------+
| deptno | dname | loc |
+--------+-----------+--------+
| 40 | Operation | Boston |
+--------+-----------+--------+
1 row in set (0.00 sec)

Query OK, 0 rows affected (0.00 sec)


Write a stored procedure which returns total salary for a particular JOB category.

mysql> select * from emp;


+-------+---------+------+--------+-------+
| empno | ename | job | deptno | sal |
+-------+---------+------+--------+-------+
| 1 | Arjun | AP | 1 | 10000 |
| 2 | Barath | ASP | 2 | 20000 |
| 3 | Aparna | ASP | 2 | 20000 |
| 4 | Karthik | AP | 16 | 10000 |
+-------+---------+------+--------+-------+
4 rows in set (0.00 sec)
mysql> delimiter $$
mysql> create procedure sumof(
-> IN jobs varchar(10),
EX NO: 7
DATE: EXCEPTION HANDLING
-> OUT total int)
-> BEGIN
-> select sum(sal)
-> into total
-> from emp
-> where job=jobs;
-> END $$
Query OK, 0 rows affected (0.00 sec)
mysql> delimiter ;
mysql> CALL sumof('ASP',@total);
Query OK, 0 rows affected (0.00 sec)

mysql> select @total;


+--------+
| @total |
+--------+
| 40000 |
+--------+
1 row in set (0.00 sec)

INFERENCE:

RESULT:

AIM:

To implement and execute PROCEDURE that handles all types of exceptions in MySQL

Database using Procedural Language concepts.

EXCEPTIONS HANDLER SYNTAX:

DECLARE handler_action HANDLER

FOR condition_value [, condition_value] ...


statement
handler_action:
CONTINUE
| EXIT
| UNDO
condition_value:
mysql_error_code
| SQLSTATE [VALUE] sqlstate_value
| condition_name
| SQLWARNING
| NOT FOUND
| SQLEXCEPTION

The DECLARE….HANDLER statement specifies a handler that deals with one or more conditions. If one of

these conditions occurs, the specified statement executes. statement can be a simple statement such as SET
var_name = value, or a compound statement written using BEGIN and ENDThe handler_action value indicates
what action the handler takes after execution of the handler statement:

•CONTINUE: Execution of the current program continues.

•EXIT: Execution terminates for the BEGIN ... END compound statement in which the handler is

declared. This is true even if the condition occurs in an inner block.

•UNDO: Not supported.

The condition_value for DECLARE ... HANDLER indicates the specific condition or class of conditions that

activates the handler:

•A MySQL error code (a number) or an SQLSTATE value (a 5-character string literal).

•A condition name previously specified with DECLARE ... CONDITION. A condition name can be

associated with a MySQL error code or SQLSTATE value.


•SQLWARNING is shorthand for the class of SQLSTATE values that begin with '01'.

•NOT FOUND is shorthand for the class of SQLSTATE values that begin with '02'.

•SQLEXCEPTION is shorthand for the class


Some common MySQL error codes and SQLSTATE codes
of SQLSTATE values that do not begin with '
MySQL SQLSTATE Error message 00', '01', or
error code code
'02'.
1011 HY000 Error on delete of „%s‟ (errno: %d)
Disk full (%s); waiting for someone to free some DUPLICATE KEY EXCEPTION
1021 HY000 space . . . mysql>create table article(art_id
1022 23000 Can‟t write; duplicate key in table „%s‟ int,tag_id int,primary key(art_id,
1027 HY000 „%s‟ is locked against change
tag_id);
1036 HY000 Table „%s‟ is read only
1048 23000 Column „%s‟ cannot be null mysql> delimiter $$;
1062 23000 Duplicate entry „%s‟ for key %d
1099 HY000 Table „%s‟ was locked with a READ lock and mysql> desc article;
can‟t be updated -> $$
1100 HY000 Table „%s‟ was not locked with LOCK +--------+---------+------+-----
TABLES +---------+-------+
1106 42000 Incorrect parameters to procedure „%s‟ | Field | Type | Null | Key | Defa
1114 HY000 The table „%s‟ is full ult | Extra |
Delayed insert thread couldn‟t get requested +--------+---------+------+-----
1150 HY000 lock for table %s +---------+-------+
1165 HY000 INSERT DELAYED can‟t be used with table | art_id | int(11) | NO | PRI | 0
„%s‟ because it is locked with LOCK TABLES | |
1242 21000 Subquery returns more than 1 row | tag_id | int(11) | NO | PRI | 0
1263 22004 Column set to default value; NULL supplied to | |
NOT NULL column „%s‟ at row %ld +--------+---------+------+-----
1264 22003 +---------+-------+
Out of range value adjusted for column „%s‟ at
row %ld 2 rows in set (0.00 sec)
1265 1000 Data truncated for column „%s‟ at row %ld
mysql> CREATE PROCEDURE in_article
1312 0A000 SELECT in a stored program must have INTO
(IN art_id INT,IN tag_id INT)
1317 70100 Query execution was interrupted
-> BEGIN
1319 42000 Undefined CONDITION: %s
-
> DECLARE CONTINUE HANDLER for 1062
-> SELECT CONCAT('Duplicate Keys(art_id,tag_id)found') AS msg;
-> INSERT INTO article(art_id,tag_id)
-> Values(art_id,tag_id);
-> select COUNT(*) from article;
-> END $$
Query OK, 0 rows affected (0.00 sec)

mysql> CALL in_article(1,1);


-> $$
+----------+
| COUNT(*) |
+----------+
| 3|
+----------+
1 row in set (0.00 sec)

Query OK, 0 rows affected (0.00 sec)

mysql> CALL in_article(1,2);


-> $$
+----------+
| COUNT(*) |
+----------+
| 4|
+----------+
1 row in set (0.00 sec)

Query OK, 0 rows affected (0.00 sec)


mysql> CALL in_article(1,1);
-> $$
+------------------------------------+
| msg |
+------------------------------------+
| Duplicate Keys(art_id,tag_id)found |
+------------------------------------+
1 row in set (0.00 sec)

+----------+
| COUNT(*) |
+----------+
| 4|
+----------+
1 row in set (0.00 sec)

Query OK, 0 rows affected (0.00 sec)

INFERENCE:
EX NO: 8 DATABASE DESIGN USING ER MODELING, NORMALIZATION
DATE:

RESULT:

AIM:

To implement. database design using ER modeling, normalization and implementation for


any application

ER- Diagram:

It is an Entity –Relationship diagram which is used to represent the relationship between different
entities. An entity is an object in the real world which is distinguishable from other objects. The
overall logical structure of a database can be expressed graphically by an ER diagram, which is built
up from following components.
Rectangles: represent entity sets.
Ellipses: represent attributes.
Diamonds: represent relationships among entity sets.
Lines: link attribute to entity sets and entity sets to relationships.

Mapping Cardinalities:

It expresses the number of entities to which another entity can be associated via a relationship set.
For a binary relationship set R between entity sets A and B. The Mapping Cardinalities must be one
of the following.
• One to one

• One to many

• Many to one
• Many to many

Consider the following schema for a Library Database:

BOOK (Book_id, Title, Publisher_Name, Pub_Year)

BOOK_AUTHORS (Book_id, Author_Name)

PUBLISHER (Name, Address, Phone)

BOOK_COPIES (Book_id, Branch_id, No-of_Copies)

BOOK_LENDING (Book_id, Branch_id, Card_No, Date_Out, Due_Date)

LIBRARY_BRANCH (Branch_id, Branch_Name, Address)

36

ER DIAGRAM
Produce the Third Normal Form of this document by normalization
0NF
• ORDER(order#, customer#, name, address, orderdate(product#, description, quantity, unitprice))

1NF

• ORDER(order#, customer#, name, address, orderdate)

• ORDER_LINE(order#, product#, description, quantity, unitprice)

2NF

• ORDER(order#, customer#, name, address, orderdate)

• ORDER_LINE(order#, product#, quantity)

• PRODUCT(product#, description, unitprice)

3NF

• ORDER(order#, customer#, orderdate)

• CUSTOMER(customer#, name, address)

• ORDER_LINE(order#, product#, quantity)

• PRODUCT(product#, description, unitprice)

INFERENCE:
EX NO: 9 DATABASE CONNECTIVITY WITH FRONT END TOOLS
DATE:

RESULT:

AIM:

To design and implement a database connectivity with front end tools for Book database
using Netbeans and mysql.

Steps:

1.Create a database in Mysql


2.Use the database.
3.Create three tables books,authors and book_by_author with SQL DDL Comands.
4.Insert few records in the tables mentioned above.
5. Open the NetBeans IDE and create a Java Project
6. Add the MySQL JDBC Driver
7. Create an application by connecting to the database and Execute the SQL query
processing statements and generate the query result

Database Creation:

mysql>CREATE testdb;
mysql>USE testdb;

mysql>create table books(isbn varchar(20) primary key,title varchar(50),

edition varchar(20),price float(10,2));


mysql>create table authors(author_id int primary key,author_name
varchar(50));
mysql>create table book_by_author(isbn varchar(20),author_id int,foreign
key(isbn)references books(isbn),foreign key(author_id) references
authors(author_id));
Insertion:
msql>insert into books values('123456','Discrete Math','Second',56.78);

msql>insert into books values('102938','Numerical Methods','Third',98.46);

msql>insert into authors values(1,'CS Liu');

mysql>insert into authors values(2,'N Deo');


mysql>insert into book_by_author values('123456',1);

mysql>insert into book_by_author values('123456',2);

mysql>commit;
Open the NetBeans IDE and create a Java Project

package javaapplication1;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class JavaApplication1 {


static final String DB_URL =
"jdbc:mysql://localhost:3306/test";
static final String DB_DRV =
"com.mysql.jdbc.Driver";
static final String DB_USER = "Rajan";
static final String DB_PASSWD = "Rajan";

/**
* @param args the command line arguments
*/
public static void main(String[] args) {
Connection connection = null;
Statement statement = null;
ResultSet resultSet = null;

try{
connection=DriverManager.getConnection
(DB_URL,DB_USER,DB_PASSWD);
statement=connection.createStatement();
resultSet=statement.executeQuery
("SELECT * FROM books");
while(resultSet.next()){
System.out.printf("%s\t%s\t%s\t%f\n",
resultSet.getString(1),
resultSet.getString(2),
resultSet.getString(3),
resultSet.getFloat(4));
}

}catch(SQLException ex){
}finally{
try {
resultSet.close();
statement.close();
connection.close();
} catch (SQLException ex) {
}
}
}
}
OUTPUT:

Fields Type Description


Name Varchar(20) Name of the Student
Rollno Varchar(20) Roll Number of the Student
Regno Varchar(20) Register Number of the Student
DOB date Date Of Birth of the Student
Fields Type Description
Rollno Varchar(20) Roll number of the student INFERENCE:
Phy Int(11) Mark 1-Physics
Chem Int(11) Mark 2-Chemistry
DBMS 2)Attendence:- Int(11) Mark 3-DBMS
Fields Type Description
Rollno Varchar(20) Roll number of the student
Adate date Attendance Date(Absent date)
EX NO: 10
CASE STUDY USING REAL LIFE DATABASE
DATE:
3)Marks:- APPLICATIONS

RESULT:
To create a Mini project to implement the Operations of a Student Database using JAVA as
front-end and MYSQL as back-end.

AIM:-
DESIGN PLAN

The Design plan consists of the following:

Project Plan

Software requirement Analysis

Implementation and Coding

Software testing

Software Debugging

Conclusion

Tables:-

1)Biodata:-

Steps to Connect Java With MYSQL:-

1) Create a database in MYSQL.

2) Grant all privileges to user by providing password.

3) Import the packages: Requires that you include the packages containing the JDBC classes
needed for database programming. Most often using import java.sql.* will suffice.

4) Register the JDBC driver:- Requires that you initialize a driver so you can open a
communication channel with the database.
5) Open a connection: Requires using the DriverManager.getConnection() method to create a
Connection object, which represents a physical connection with the database.
6) Execute a Query: Requires using an object of type statement for building and submitting an SQl

statement to the database.


7) Extract data from ResultSet: Requires that you use the appropriate ResultSet.getXXX() method

to retrieve the data from the ResultSet


Steps To Import MYSQL Connector Into Your Project:-

1) Click project properties

2) Click on libraries and then ADD Library

3) Click on import,then you may many JARS available

4) Select the MYSQL JDBC driver and import it

Table Creation:-

mysql> use sunil;


Database changed

mysql> create table biodata(Name varchar(20),Rollnovarchar(20) primary key,Re


gnovarchar(20),DOB date);
Query OK, 0 rows affected (0.08 sec)

mysql> create table attendence(rollnovarchar(20),adate date);


Query OK, 0 rows affected (0.07 sec)

mysql> create table marks(rollnovarchar(20),phyint,chemint,dbmsint);


Query OK, 0 rows affected (0.06 sec)

mysql> grant all on sunil to root@localhost identified by 'rooty';


Query OK, 0 rows affected (0.14 sec)

CODE TO CONNECT TO THE DATABASE:-


Importing packages:-

Importjava.sql.*;
Importjavax.swing.JOptionPane;

Importjavax.swing.table.DefaultTableModel;

Button Coding:-

private void insertrecordActionPerformed(java.awt.event.ActionEventevt) {

try

{Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/sunil","root","rooty");

Statement stmt = conn.createStatement();


Class.forName("java.sql.Driver");

String nam = name.getText();

String roll = rollno.getText();

String regn = regno.getText();

String dbt = dob.getText();

stmt.executeUpdate("Insert into biodata values ('"+nam+"','"+roll+"',"+regn+" , '"+dbt+"')");

catch(Exception s){

JOptionPane.showMessageDialog(null, s.getMessage());

private void clearfieldsActionPerformed(java.awt.event.ActionEventevt) {


name.setText("");

rollno.setText("");

regno.setText("");

dob.setText("");

private void searchrollnoActionPerformed(java.awt.event.ActionEventevt) {

try

{Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/sunil","root","rooty");

Statement stmt = conn.createStatement();

Class.forName("java.sql.Driver");

String roll = rollno.getText();

ResultSetrs=stmt.executeQuery("select * from biodata where rollno='"+roll+"'");


rs.next();

name.setText(rs.getString(1));

rollno.setText(rs.getString(2));

regno.setText(rs.getString(3));

dob.setText(rs.getString(4));

catch(Exception s){
JOptionPane.showMessageDialog(null, s.getMessage());

}}

private void searchregnoActionPerformed(java.awt.event.ActionEventevt) {

try{

Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/sunil","root","rooty");

Statement stmt = conn.createStatement();

Class.forName("java.sql.Driver");

String reg = regno.getText();

ResultSetrs=stmt.executeQuery("select * from biodata where regno='"+reg+"'");

rs.next();

name.setText(rs.getString(1));

rollno.setText(rs.getString(2));

regno.setText(rs.getString(3));

dob.setText(rs.getString(4));

catch(Exception s){

JOptionPane.showMessageDialog(null, s.getMessage());

private void clearActionPerformed(java.awt.event.ActionEventevt) {

rollno1.setText("");

date.setText("");

private void searchActionPerformed(java.awt.event.ActionEventevt) {

DefaultTableModel tm = (DefaultTableModel)jTable1.getModel();

tm.setRowCount(0);

try{
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/sunil","root","rooty");

Statement stmt = conn.createStatement();

Class.forName("java.sql.Driver");

String roll = rollno1.getText();

String Query = "Select * from attendence where rollno='"+roll+"'";


ResultSetrs = stmt.executeQuery(Query);

while(rs.next()){

String n=rs.getString("rollno");

String m=rs.getString("adate");

Object[] o ={n,m};

tm.addRow(o);

catch(Exception s){

JOptionPane.showMessageDialog(null, s.getMessage());

private void submitActionPerformed(java.awt.event.ActionEventevt) {

try

{Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/sunil","root","rooty");

Statement stmt = conn.createStatement();

Class.forName("java.sql.Driver");

String roll = rollno1.getText();

String adate = date.getText();

stmt.executeUpdate("Insert into attendence values ('"+roll+"', '"+adate+"')");

catch(Exception s){

JOptionPane.showMessageDialog(null,s.getMessage());

private void submit1ActionPerformed(java.awt.event.ActionEventevt) {

try{

Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/sunil","root","rooty");

Statement stmt = conn.createStatement();


Class.forName("java.sql.Driver");

String n = rollno2.getText();
int r = Integer.parseInt(phy.getText());

int p= Integer.parseInt(chem.getText());

int d = Integer.parseInt(dbms.getText());

stmt.executeUpdate("Insert into marks values ('"+n+"',"+r+","+p+" , "+d+")");

catch(Exception s){

JOptionPane.showMessageDialog(null, s.getMessage());

private void clearmarksActionPerformed(java.awt.event.ActionEventevt) {

rollno2.setText("");

phy.setText("");

chem.setText("");

dbms.setText("");

private void marksearchActionPerformed(java.awt.event.ActionEventevt) {

try {

Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/sunil","root","rooty");

Statement stmt = conn.createStatement();

String roll = rollno2.getText();

ResultSetrs = stmt.executeQuery("select * from marks where rollno='"+roll+"'");

rs.next();

rollno2.setText(rs.getString(1));

phy.setText(Integer.toString(rs.getInt(2)));

chem.setText(Integer.toString(rs.getInt(3)));

dbms.setText(Integer.toString(rs.getInt(4)));

catch(Exception e){
JOptionPane.showMessageDialog(null, e.getMessage());

SCREEN SHOTS:

INFERENCE:

RESULT :
EX NO:11 POPULATE DATABASE IN QUERY
DATE:

CONTENT BEYOND SYLLABUS

AIM:

To Write any Populate Database in Query.

INFERENCE
EX NO:13
NO:12 CALCULATE AREA OF CIRCLE USING PL/SQL PROGRAM
DATE: REPORTS USING SQL

RESULT:

AIM:

To prepare reports using database table in SQL.

EXAMPLE 1
SQL> SET LINESIZE 80
SQL> TTITLE 'PIT STAFF'
SQL> select * from emp;

EXAMPLE 2

SQL> ttitle 'Employee Details'


SQL> btitle ''End”
SQL> column mark heading 'salary' format$9999.99
SQL> clear computes
computes cleared
SQL> break on title skip 2
SQL> compute sum of Salary on title
SQL> select * from emp order by empno,ename,designatin,salary;

Employee Details

INFERENCE

RESULT:
AIM:

To write a pl/sql code block to calculate the area of a circle for a value of radius varying from
3 to 7. Store the radius and the corresponding values of calculated area in an empty table named
areas, consisting of two columns radius & area .

Procedure:

Step 1: Create a table named areas with radius and area

Step 2: Initialize values to pi, radius and area


Step 3 :Calculate the area using while loop. Display the result.

INFERENCE

RESULT

You might also like