Dbms Lab Manual1
Dbms Lab Manual1
Dbms Lab Manual1
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.
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.
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.
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:
MariaDB provides an alternative syntax for inserting a new row into a table using the set clause:
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.
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 Emp ( EmpNo int(5), EName VarChar(15), Job Char(10) unique, DeptNo int(3),sal float(7,2),
foreign key(DeptNo) REFERENCES dept(deptno));
List the records in the emp table orderby salary in ascending order.
List the records in the emp table orderby salary in descending order.
Display deptno from the table employee avoiding the duplicated values.
NUMERIC FUNCTION
ROUND(15.6789)
--------------
16
CEIL(23.20)
-----------
24
FLOOR(34.56)
------------
34
TRUNC(15.56743)
---------------
15
SIGN(-345)
----------
-1
SQL> select abs(-70)from dual;
ABS(-70)
---------
70
MATH FUNCTION:
ABS(45)
---------
45
POWER(10,12)
------------
1.000E+12
MOD(11,5)
---------
EXP(10)
---------
22026.466
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;
AVG() Syntax
SELECT AVG(column_name)
FROM table_name
WHERE condition;
SUM() Syntax
SELECT SUM(column_name)
FROM table_name
WHERE condition;
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
ORDERS TABLE
CUSTOMER TABLE
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
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
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
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
Table:Depart
mysql> create table depart(deptno int,dname char(12),loc char(12));
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)
Table:Book
Table:Issue
+----------+------------+------+------+
| 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)
JOIN COMMANDS
EQUI-JOIN
Display the employee details, departments that the departments are same in both the emp and dept.
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
| staff_id |
+----------+
| 12 |
+----------+
1 row in set (0.00 sec)
INFERENCE:
RESULT:
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)
mysql> delimiter ;
mysql> CALL getin('Boston');
+--------+-----------+--------+
| deptno | dname | loc |
+--------+-----------+--------+
| 40 | Operation | Boston |
+--------+-----------+--------+
1 row in set (0.00 sec)
INFERENCE:
RESULT:
AIM:
To implement and execute PROCEDURE that handles all types of exceptions in MySQL
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:
•EXIT: Execution terminates for the BEGIN ... END compound statement in which the handler is
The condition_value for DECLARE ... HANDLER indicates the specific condition or class of conditions that
•A condition name previously specified with DECLARE ... CONDITION. A condition name can be
•NOT FOUND is shorthand for the class of SQLSTATE values that begin with '02'.
+----------+
| COUNT(*) |
+----------+
| 4|
+----------+
1 row in set (0.00 sec)
INFERENCE:
EX NO: 8 DATABASE DESIGN USING ER MODELING, NORMALIZATION
DATE:
RESULT:
AIM:
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
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
2NF
3NF
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:
Database Creation:
mysql>CREATE testdb;
mysql>USE testdb;
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;
/**
* @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:
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
Project Plan
Software testing
Software Debugging
Conclusion
Tables:-
1)Biodata:-
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
Table Creation:-
Importjava.sql.*;
Importjavax.swing.JOptionPane;
Importjavax.swing.table.DefaultTableModel;
Button Coding:-
try
catch(Exception s){
JOptionPane.showMessageDialog(null, s.getMessage());
rollno.setText("");
regno.setText("");
dob.setText("");
try
Class.forName("java.sql.Driver");
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());
}}
try{
Class.forName("java.sql.Driver");
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());
rollno1.setText("");
date.setText("");
DefaultTableModel tm = (DefaultTableModel)jTable1.getModel();
tm.setRowCount(0);
try{
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/sunil","root","rooty");
Class.forName("java.sql.Driver");
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());
try
Class.forName("java.sql.Driver");
catch(Exception s){
JOptionPane.showMessageDialog(null,s.getMessage());
try{
String n = rollno2.getText();
int r = Integer.parseInt(phy.getText());
int p= Integer.parseInt(chem.getText());
int d = Integer.parseInt(dbms.getText());
catch(Exception s){
JOptionPane.showMessageDialog(null, s.getMessage());
rollno2.setText("");
phy.setText("");
chem.setText("");
dbms.setText("");
try {
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:
AIM:
INFERENCE
EX NO:13
NO:12 CALCULATE AREA OF CIRCLE USING PL/SQL PROGRAM
DATE: REPORTS USING SQL
RESULT:
AIM:
EXAMPLE 1
SQL> SET LINESIZE 80
SQL> TTITLE 'PIT STAFF'
SQL> select * from emp;
EXAMPLE 2
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:
INFERENCE
RESULT