CS8481 - Database Management Systems Laboratory: Student Lab Manual
CS8481 - Database Management Systems Laboratory: Student Lab Manual
Submitted By
Mr. G. Saravanakumar
Assistant Professor
Department of Computer Science and Engineering
VISION AND MISSION
COMPUTER SCIENCE AND ENGINEERING DEPARTMENT
VISION
Emerge as Centre of excellence in Computer Science and Engineering through quality education,
research and innovation.
MISSION
To provide quality engineering education to the students through state-of-art facilities in
Computer Science and Engineering.
To enrich students knowledge towards research, entrepreneur skill and employability.
To inculcate value-based, socially committed professionalism to the cause of overall
development of students and society.
Prepared By Approved by
AIM: The aim of this laboratory is to inculcate the abilities of applying the principles of the
database management systems. This course aims to prepare the students for projects where a
proper implementation of databases will be required.
OBJECTIVES:
To understand data definitions and data manipulation commands
To learn the use of nested and join queries
To understand functions, procedures and procedural extensions of data bases
To be familiar with the use of a front end tool
To understand design and implementation of typical database applications
EXPERIMENTS:
1. Data Definition Commands, Data Manipulation Commands for inserting, deleting, updating
and retrieving Tables and Transaction Control statements
2. Database Querying – Simple queries, Nested queries, Sub queries and Joins
3. Views, Sequences, Synonyms
4. Database Programming: Implicit and Explicit Cursors
5. Procedures and Functions
6. Triggers
7. Exception Handling
8. Database Design using ER modeling, normalization and Implementation for any application
9. Database Connectivity with Front End Tools
10. Case Study using real life database applications
TOTAL: 60 PERIODS
OUTCOMES:
Upon completion of the course, the students will be able to:
Use typical data definitions and manipulation commands.
Design applications to test Nested and Join Queries
Implement simple applications that use Views
Implement applications that require a Front-end Tool
Critically analyze the use of Tables, Views, Functions and Procedures
Experiment No 1:
Data Definition Commands, Data Manipulation Commands for inserting, deleting,
updating and retrieving Tables and Transaction Control statements
Aim:
To execute Data Definition Commands, Data Manipulation Commands for
inserting,deleting, updating and retrieving Tables and Transaction Control statements.
Creation:
Create command is used to create a new table.
Syntax
create table <table name>
{
fieldname-1 datatype constraints if any,
fieldname-2 datatype constraints if any,
…….
fieldname-n datatype constraints if any,
};
DESCRIBING TABLE
Desc <tablename>;
Constraints:
The three types of constraints are Domain Integrity Constraints, Entity Integrity Constraints, and
Referential Integrity Constraints. Integrity Constraints are used to enforce rules that the columns
in a table have to conform with. It is a mechanism used by Oracle to prevent invalid data entry
into the table.
1. Domain Integrity Constraints
a. Not Null Constraint – The enforcement of Not Null Constraints in a table ensures that
the table contains values.
b. Check Constraint – Allow only a particular range of values
DROP TABLE
1. All data and structure in the table is deleted
2. Any pending transactions are committed.
3. All indexes are dropped.
4. We can not rollback the drop table statement.
Exercise:
1. Create a table for student database, which has the following attributes attributes such as,
register number of the students, name of the students, date of birth, department, year of
study, address.
2. Display the structure of the table.
3. Add a new field phone number to the table.
4. Modify the size of address field in the table.
5. Drop the table.
UPDATE - It is used to alter the column values in a table. A single column may be updated or
more than one column could be updated.
Syntax:
update <table name> set(fieldname-1 = value, fieldname-2 = value,…,fieldname-n = value)
[WHERE <condition/expression>];
DELETE - After inserting row in a table we can also delete them if required. The delete
command consists of a from clause followed by an optional where clause.
Syntax:
delete from <table name> [where <condition/expression>];
TRUNCATE - If there is no further use of records stored in a table and the structure has to be
retained, then the records alone can be deleted.
Syntax:
Truncate table <table name>
Commit: This command is used to save the changes made by the DML statements.
Roll Back: 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.
SAVEPOINT: This command is used to temporarily save a transaction so that you can rollback
to that point whenever required.
Exercise:
1. Create a table that contains information about Students with fields Regno, Name, DOB, Age,
Sex, Department, Subject 1, Subject 2, Subject 3, Total. The Regno is a unique field and the
sex should contain the value either ‘M’ or ‘F’.
2. Insert records in the table.
3. Add a new field average to the student table.
4. Update the total and Average of the Students.
5. Display the student details
6. Display the student details whose average is greater than 70
7. Display the details of the students whose average is between 70 and 80.
8. Find the students whose name starts with the letter ‘A’.
9. Display the student name without duplication.
10. Delete the students whose name starts with the letter ‘C’.
11. Create 3 save points
12. Rollback to the savepoints.
Result:
Thus the DDL, DML and TCL command were executed and the outputs are verified.
Experiment No: 02
Database Querying – Simple queries, Nested queries, Sub queries and Joins
AIM:
To write queries using Set operations, to write nested queries and also to write queries using
clauses such as GROUP BY, ORDER BY, etc. and retrieving information by joining tables.
NESTED QUERY: - A nested query makes use of another sub-query to compute or retrieve the
information.
UNION - OR
INTERSECT - AND
EXCEPT - NOT
Order by : The order by clause is used to display the results in sorted order.
Group by : The attribute or attributes given in the clauses are used to form groups. Tuples with
the same value on all attributes in the group by clause are placed in one group.
Having: SQL applies predicates (conditions) in the having clause after groups have been formed,
so aggregate function be used.
Queries:
1. Create a the following tables
a. Employee ( Employee_number, EName, Street, City)
b. Works(Ename, Cname, salary)
c. Manager(Cname, MName)
2. Find all the employees who live in the same city as the company for which they work.
3. Find the second maximum salary of the employee.
4. Find the employees who earn more than the average salary of all employees of their
company.
5. Find the company that has the smallest payroll.
6. Find the company that has more number of employees.
7. Apply joins between employee and Manager.
Employee:
Works
Company
COMPANY_NAME CITY
SAEC Ramnad
TCS Chennai
Infosys Chennai
Manager:
EMP_NAME MANAGER_NAME
Ragav Charli
Anand Charli
Mani Murali
Siva Sampath
1. Find all the employees who live in the same city as the company for which they work.
EMP_NAME COMPANY_NAME
Ragav SAEC
Siva TCS
2. Find the second maximum salary of the employee.
MAX(SALARY)
38000
3. Find the employees who earn more than the average salary of all employees of their
company.
select emp_name,salary from works where salary > (select avg(salary) from works)
EMP_NAME SALARY
Ragav 50000
select company_name,salary from works where salary =(select min(salary) from works)
COMPANY_NAME SALARY
SAEC 35000
COMPANY_NAME COUNT(EMP_NAME)
Infosys 1
SAEC 2
TCS 1
Result:
The the queries for nested, sub queries and join are executed and their outputs are
verified.
Experiment No: 03
View:
In SQL a view is a virtual table based on the result-set of an SQL statement. A view
contains rows and columns, just like a real table. The fields in a view are fields from one or more
real tables in the database. You can add SQL functions, WHERE, and JOIN statements to a view
and present the data as if the data were coming from one single table.
Syntax:
CREATE VIEW view_name AS
SELECT column_name(s)
FROM table_name
WHERE condition;
Example:
CREATE VIEW Outstanding as
Select * from students
where grade = ‘S’;
Synonym:
A synonym is an alternative name for objects such as tables, views, sequences, stored
procedures, and other database objects.
Syntax:
CREATE [OR REPLACE] [PUBLIC] SYNONYM [schema .] synonym_name
FOR [schema .] object_name [@ dblink];
Where
OR REPLACE allows you to recreate the synonym (if it already exists) without having to
issue a DROP synonym command.
PUBLIC means that the synonym is a public synonym and is accessible to all users.
Remember though that the user must first have the appropriate privileges to the object to
use the synonym.
schema is the appropriate schema. If this phrase is omitted, Oracle assumes that you are
referring to your own schema.
object_name is the name of the object for which you are creating the synonym. It can be
one of the following:
table
view
sequence
stored procedure
function
package
materialized view
java class schema object
user-defined object
synonym
Example:
CREATE PUBLIC SYNONYM suppliers FOR app.suppliers;
Retrieving from Synonym:
SELECT * FROM suppliers;
Drop synonym
DROP [PUBLIC] SYNONYM [schema .] synonym_name [force];
Where
PUBLIC allows you to drop a public synonym.
force will force Oracle to drop the synonym even if it has dependencies. It is probably
not a good idea to use force as it can cause invalidation of Oracle objects
Example:
DROP PUBLIC SYNONYM suppliers;
Sequence:
In Oracle, you can create an auto number field by using sequences. A sequence is an
object in Oracle that is used to generate a number sequence. This can be useful when you need to
create a unique number to act as a primary key.
Syntax
CREATE SEQUENCE sequence_name
MINVALUE value
MAXVALUE value
START WITH value
INCREMENT BY value
CACHE value;
Example:
CREATE SEQUENCE supplier_seq
MINVALUE 1
START WITH 1
INCREMENT BY 1
CACHE 20;
INSERT INTO suppliers (supplier_id, supplier_name) VALUES (supplier_seq.NEXTVAL,
'Kraft Foods');
*Supplier_seq.NEXTVAL provides the next value in the sequence to the supplier_id field.
Drop Sequence:
Syntax:
DROP SEQUENCE sequence_name;
Queries:
1. Create a view Manager from Employee table with field Employee Id, Name and
Designation.
SQL/> create view manager as
Select * from employee;
Output:
View created
2. Display all information from the view.
SQL/> Select * from Manager;
4. Create a synonym for employee table, Make it as public and available to all.
SQL/>create public synonym maxi for employee;
Output:
Synonym created
Output:
Sequence created.
Result:
Thus the view, synonyms, sequence, index are created and executed successfully and its outputs
are verified.
Experiment No: 04
PL/SQL
Aim:
LOOPING STATEMENTS:-
The SQL supports number of looping statements like GOTO, FOR, WHILE & LOOP.
GOTO STATEMENTS
<<LABEL>>
SET OF STATEMENTS
GOTO LABEL;
FOR LOOP
FOR <VAR> IN [REVERSE] <INI_VALUE>..<END_VALUE>
SET OF STATEMENTS
END LOOP;
WHILE LOOP
WHILE (CONDITION) LOOP
SET OF STATEMENTS
END LOOP;
LOOP STATEMENT
LOOP
SET OF STATEMENTS
IF (CONDITION) THEN
EXIT
SET OF STATEMENTS
END LOOP;
While using LOOP statement, we have take care of EXIT condition, otherwise it may go into
infinite loop.
Programs:
1. Write a PL/SQL Program to find the biggest of three numbers.
2. Write a PL/SQL Program to generate number series.
3. Write a PL/SQL Program to display the number series using while loop statements.
4. Write a PL/SQL Program to generate Fibonacci series.
5. Write a PL/SQL Program to check then given number is Armstrong number or not.
6. Write a PL/SQL Program to find the reverse of the given number.
7. Write a PL/SQL program to generate number series.
Programs:
TO DISPLAY HELLO MESSAGE
2
3
4
PL/SQL procedure successfully completed.
RESULT
Thus the basic programs in PL/SQL block has been executed and verified.
Experiment No:05
PL/SQL Cursors
Aim:
Procedure:
Oracle creates a memory area, known as the context area, for processing an SQL statement,
which contains all the information needed for processing the statement.
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.
Implicit cursors
Explicit cursors
Implicit Cursors
Implicit cursors are automatically created by Oracle whenever an SQL statement is executed,
when there is no explicit cursor for the statement. Programmers cannot control the implicit
cursors and the information in it.
Explicit Cursors
Explicit cursors are programmer-defined cursors for gaining more control over the context
area. An explicit cursor should be defined in the declaration section of the PL/SQL Block. It is
created on a SELECT Statement which returns more than one row.
CURSOR c_customers IS
OPEN c_customers;
CLOSE c customers;
The following table provides the description of the most used attributes −
1 %FOUND
%NOTFOUND
%ISOPEN
3 Always returns FALSE for implicit cursors, because Oracle closes the SQL cursor
automatically after executing its associated SQL statement.
%ROWCOUNT
4 Returns the number of rows affected by an INSERT, UPDATE, or DELETE statement,
or returned by a SELECT INTO statement.
Example
Following is a complete example to illustrate the concepts of explicit cursors;
DECLARE
c_id customers.id%type;
c_name customerS.No.ame%type;
c_addr customers.address%type;
CURSOR c_customers is
BEGIN
OPEN c_customers;
LOOP
FETCH c_customers into c_id, c_name, c_addr;
END LOOP;
CLOSE c_customers;
END;
Exercise:
1. Create a table worker with attributes worker id, name, job, dept_no, and salary. The job
must be a manager or clerk or assistant.
2. Insert appropriate values in the table.
3. Write a PL/SQL program to display the content of the table.
4. Write a PL/SQL program to insert s row in the table.
5. Write a cursor program to insert the values into the table.
6. Write a cursor program to update the salary of manager as 500, clerk as 200 and assistant
as 100 in the worker table until the records are found.
7. Write a cursor program to count the number of rows fetched.
Programs:
declare
e_no emp.eno%type;
e_name emp.ename%type;
sal emp.salary%type;
dep emp.dept%type;
cursor c1 is select eno,ename,salary,dept from emp;
begin
open c1;
loop
fetch c1 into e_no,e_name,sal,dep;
dbms_output.put_line(e_no||e_name||sal||dep);
exit when c1%notfound;
end loop;
close c1;
end;
declare
e_no emp.eno%type;
e_name emp.ename%type;
sal emp.salary%type;
dep emp.dept%type;
cursor c1 is select eno,ename,salary,dept from emp;
begin
e_no:=&e_no;
e_name:='&e_name';
sal:=&sal;
dep:='&dep';
open c1;
insert into emp values(e_no,e_name,sal,dep);
close c1;
end;&dep';
open c1;
insert into emp values(e_no,e_name,sal,dep);
end loop;
close c1;
end;
declare
cursor c1 is select eno,ename,salary,dept from emp;
e_no emp.eno%type;
e_name emp.ename%type;
sal emp.salary%type;
dep emp.dept%type;
rno number(3);
begin
open c1;
loop
fetch c1 into e_no,e_name,sal,dep;
if c1%found then
rno:=c1%rowcount;
end if;
end loop;
dbms_output.put_line('Row Count is = '||rno);
close c1;
end;
Result:
Thus the PL/SQL program for implicit and explicit cursor is performed and the outputs
are verified.
Experiment No: 06
AIM:
To solve the given problem statements using procedures.
PL/SQL PROCEDURES:
Procedures are the subprograms that do not return a value directly. It is mainly used to
perform action.
SYNTAX:
CREATE [OR REPLACE] PROCEDURE procedure_name
[(parameter_name [IN | OUT | IN OUT] type [, ...])]
{IS | AS}
BEGIN
< procedure_body >
END procedure_name;
Where,
procedure-name specifies the name of the procedure.
[OR REPLACE] option allows the modification of an existing procedure.
The optional parameter list contains name, mode and types of the
parameters. IN represents the value that will be passed from outside and OUT represents
the parameter that will be used to return a value outside of the procedure.
procedure-body contains the executable part.
The AS keyword is used instead of the IS keyword for creating a standalone procedure.
PL/SQL Functions:
A PL/SQL function is same as a procedure except that it returns a value. A standalone function is
created using the CREATE FUNCTION statement.
SYNTAX
CREATE [OR REPLACE] FUNCTION function_name (parameter_name [IN | OUT | IN OUT]
type [, ...])
RETURN return_datatype
{IS | AS}
BEGIN
<function_body>
END;
Program:
1. Write a stand alone procedure in pl/sql.
2. Write a procedure to find the maximum of two numbers using IN and Out
parameter.
3. Write a procedure to find the square of a number usinf IN and OUT parameter.
PROCEDURE squareNum(x IN OUT number) IS
BEGIN
x := x * x;
END;
DECLARE
a number;
BEGIN
a:= 23;
squareNum(a);
dbms_output.put_line(' Square of (23): ' || a);
END;
4. Write a standalone function to find the total number of records in the table.
CREATE OR REPLACE FUNCTION totalCustomers
RETURN number IS
total number(2) := 0;
BEGIN
SELECT count(*) into total
FROM customers;
RETURN total;
END;
Calling a function:
DECLARE
c number(2);
BEGIN
c := totalCustomers();
dbms_output.put_line('Total no. of Customers: ' || c);
END;
DECLARE
a number;
b number;
c number;
FUNCTION findMax(x IN number, y IN number)
RETURN number
IS
z number;
BEGIN
IF x > y THEN
z:= x;
ELSE
Z:= y;
END IF;
RETURN z;
END;
BEGIN
a:= 23;
b:= 45;
c := findMax(a, b);
dbms_output.put_line(' Maximum of (23,45): ' || c);
END;
6. Write a recursive function to find the factorial of the given number.
DECLARE
num number;
factorial number;
BEGIN
num:= 6;
factorial := fact(num);
dbms_output.put_line(' Factorial '|| num || ' is ' || factorial);
END;
Result:
Thus PL/SQL Procedures and functions were created and its outputs are verified.
Experiment No:7
Triggers
Aim:
To write a PL/SQL program to perform high level language extension using trigger.
Procedure:
Trigger is a statement that executes automatically as a side effect of modification of the
database. Triggers are, in fact, written to be executed in response to any of the following events −
Triggers can be defined on the table, view, schema, or database with which the event is
associated.
Benefits of Triggers:
Triggers can be written for the following purposes −
Where,
{BEFORE | AFTER | INSTEAD OF} − This specifies when the trigger will be executed.
The INSTEAD OF clause is used for creating trigger on a view.
{INSERT [OR] | UPDATE [OR] | DELETE} − This specifies the DML operation.
[OF col_name] − This specifies the column name that will be updated.
[ON table_name] − This specifies the name of the table associated with the trigger.
[REFERENCING OLD AS o NEW AS n] − This allows you to refer new and old values
for various DML statements, such as INSERT, UPDATE, and DELETE.
[FOR EACH ROW] − This specifies a row-level trigger, i.e., the trigger will be executed
for each row being affected. Otherwise the trigger will execute just once when the SQL
statement is executed, which is called a table level trigger.
WHEN (condition) − This provides a condition for rows for which the trigger would fire.
This clause is valid only for row-level triggers.
Exercise 01:
The details about the students mark are being in the stu table with attributes. Name, Rollno,
mark, Mark2, Mark3.
The stu1 table consists of attributes, Rollno, Total, Average, Result.
The details of the first table are being given in the prompt by the user. The total, average are
processed for currently processed row in the stu table using after insert on trigger the values are
placed in the table stu1.
Trigger:
CREATE or REPLACE TRIGGER student
AFTER INSERT ON stu
REFERENCING OLD AS o NEW AS n
FOR EACH ROW
declare
total number(3);
avge number(5,2);
result varchar2(10);
begin
total:=:n.mark1+:n.mark2+:n.mark4;
avge:=total/3;
if (:n.mark1>=50 and :n.mark2>=50 and :n.mark3>=50) then
result:='pass'
else
result:='fail'
end if;
insert into stu1 values(:n.rollno,total,avge,result);
end;
Trigger created
SQL>insert into st1 values(‘raja’,004,100,99,90)
1 row created
Exercise 2:
Create a table customer with the following fields Id, Name, Age, Address, and Salary.
Write a trigger to display the difference in salary when the following operations such as Insert,
Delete or Update take place in the above table.
Trigger:
PL/SQL Exception:
System-defined exceptions
User-defined exceptions
SYNTAX
DECLARE
<declarations section>
BEGIN
<executable command(s)>
EXCEPTION
<exception handling goes here >
WHEN exception1 THEN
exception1-handling-statements
WHEN exception2 THEN
exception2-handling-statements
WHEN exception3 THEN
exception3-handling-statements
........
WHEN others THEN
exception3-handling-statements
END;
Raising Exceptions:
Exceptions are raised by the database server automatically whenever there is any internal
database error, but exceptions can be raised explicitly by the programmer by using the
command RAISE.
DECLARE
exception_name EXCEPTION;
BEGIN
IF condition THEN
RAISE exception_name;
END IF;
EXCEPTION
WHEN exception_name THEN
statement;
END;
User-defined Exceptions
PL/SQL allows you to define your own exceptions according to the need of your program. A
user-defined exception must be declared and then raised explicitly, using either a RAISE
statement or the procedure DBMS_STANDARD.RAISE_APPLICATION_ERROR.
Syntax:
DECLARE
my-exception EXCEPTION;
PROBLEM STATEMENT:
1. Create a table customer with fields customer id, customer name and customer address.
Program:
DECLARE
c_id cust.id%type;
c_name cust.name%type;
BEGIN
c_id:=&c_id;
SELECT id,name INTO c_id,c_name FROM cust
WHERE id=c_id;
DBMS_OUTPUT.PUT_LINE('ID = '||c_id);
DBMS_OUTPUT.PUT_LINE('Name = '||c_name);
EXCEPTION
WHEN NO_DATA_FOUND THEN
DBMS_OUTPUT.PUT_LINE('Enter the correct id number');
WHEN OTHERS THEN
DBMS_OUTPUT.PUT_LINE('Invalid data');
END;
2. Write a PL/SQL Program that invokes exception when record is not found in the table.
DECLARE
c_id cust.id%type;
c_name cust.name%type;
invalid_exception EXCEPTION;
BEGIN
c_id:=&c_id;
IF c_id<=0 THEN
RAISE invalid_exception;
ELSE
SELECT id,name INTO c_id,c_name FROM cust
WHERE id=c_id;
DBMS_OUTPUT.PUT_LINE('ID = '||c_id);
DBMS_OUTPUT.PUT_LINE('Name = '||c_name);
END IF;
EXCEPTION
WHEN INVALID_EXCEPTION THEN
DBMS_OUTPUT.PUT_LINE('Enter the Id number greater than Zero');
WHEN NO_DATA_FOUND THEN
DBMS_OUTPUT.PUT_LINE('Enter the correct id number');
WHEN OTHERS THEN
DBMS_OUTPUT.PUT_LINE('Invalid data');
END;
Result:
Thus the PL/SQL program for exception handling is performed and the outputs are verified.
Experiment No:09
Database Design using ER modeling, normalization and Implementation for any
application
Aim:
To design a database using ER modeling, normalization and Implementation for any
application.
Entity Set:
An entity set is a set of entities of the same type that share the same properties.
Attributes:
Attribute types:
Relationship Set:
ER Diagram:
Lines link attributes to entity sets and entity sets to relationship sets.
Draw a ER diagram for Hospital management identify the relationship between the entity set and
also convert the ER diagram into table.
1.Patient(Pid,p,PName, PDiagnosis,PAddress)
2.Hospital(Hosp-id,Hos-name,Haddress,Hcity)
3. Doctor(Did,Dname,Qualification,salary)
4.MediacalRecord(record-id,Date-of-examination,problem)
Result:
Thus the database was designed using ER model, normalized and converted into table
successfully.
Experiment No : 10
Aim:
2. File->New Project
4. Give Project Name and Project Location->Finish. The new project Environment is created
5. In Project right click the source package and select New JFrame Form
7. Design the form as per the project requirements using Swing controls like Label, TextFiled,
8. In Project right click the Libraries and add the JAR file “mysql-connector-java-5.1.47.jar” in your
Project
Design Window
Code
/*
*/
/*
* NewJFrame.java
*
* Created on Mar 8, 2019, 2:46:43 PM
*/
/**
* @author root
*/
import java.sql.*;
import javax.swing.DefaultListModel;
import javax.swing.JList;
public NewJFrame() {
initComponents();
*/
@SuppressWarnings("unchecked")
jTable1.setModel(new javax.swing.table.DefaultTableModel(
},
new String [] {
));
jScrollPane1.setViewportView(jTable1);
jTable2.setModel(new javax.swing.table.DefaultTableModel(
},
new String [] {
));
jScrollPane2.setViewportView(jTable2);
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jLabel1.setText("Roll No");
jLabel2.setText("Name");
jButton1.setText("Save");
jButton1.addActionListener(new java.awt.event.ActionListener() {
});
jButton2.setText("Show");
jButton2.addActionListener(new java.awt.event.ActionListener() {
jButton2ActionPerformed(evt);
});
jList1.setModel(new javax.swing.AbstractListModel() {
String[] strings = { "Item 1", "Item 2", "Item 3", "Item 4", "Item 5" };
});
jScrollPane3.setViewportView(jList1);
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel2)
.addComponent(jLabel1)))
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jButton2)
.addComponent(jButton1))))
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING,
false)
.addComponent(jTextField2)
.addContainerGap(91, Short.MAX_VALUE))))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jLabel1)
.addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel2)
.addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jButton1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 35,
Short.MAX_VALUE)
.addComponent(jButton2)
.addGroup(layout.createSequentialGroup()
.addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap())))
);
pack();
}// </editor-fold>
Class.forName("com.mysql.jdbc.Driver");
preparedStatement.setInt(1, Integer.parseInt(jTextField1.getText()));
preparedStatement.setString(2, jTextField2.getText());
//preparedStatement.setString(3, "Test3");
preparedStatement.executeUpdate();
preparedStatement.close();
conn.close();
}catch(SQLException se){
System.out.println(se);
}catch(Exception e){
System.out.println(e);
}
}
try{
Class.forName("com.mysql.jdbc.Driver");
while (resultSet.next()) //go through each row that your query returns
jList1.setModel(model);
resultSet.close();
statement.close();
conn.close();
}catch(SQLException se){
}catch(Exception e){
System.out.println(e);
/**
*/
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
*/
try {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE,
null, ex);
java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE,
null, ex);
java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE,
null, ex);
//</editor-fold>
java.awt.EventQueue.invokeLater(new Runnable() {
new NewJFrame().setVisible(true);
});
1. In Project Services, Expand the DataBases and right click in Drives to add MtSql Driver
2. Select New Driver and click “ADD” button to add the “mysql-connector-java-5.1.47.jar” from
3. Right click the added driver in the drivers list and click connect using menu
5. Put values to drivers, host, port, database, user and Password. The sample connection wizard shown
below
6. The click Test Connection Button, once succeeded that will shown below as.
7. Then click Finish Button. The new database driver is now added in the Data Base List
Result:
Thus the front end tool Java is connected with MySql using JDBC.