Chapter 6: Database Connectivity (XII-IP)
Introduction
Chapter 6:
Database Connectivity
Informatics Practices
Class XII (CBSE Board)
Revised as per
CBSE
Curriculum
2015
Visit www.ip4you.blogspot.com for more….
Authored By:- Rajesh Kumar Mishra, PGT (Comp.Sc.)
Kendriya Vidyalaya Upper Camp, Dehradun (Uttarakhand)
e-mail : rkmalld@gmail.com
What is JDBC ?
Adding MySQL JDBC Driver in NetBeans IDE
JDBC is JAVA’s Database connection driver interface
which performs the following task for the
application.
 Establish a connection with a Database.
 Send SQL request (Query) to a Database Server.
 Returns Result obtained against Query.
FrontEnd
BackEnd
JDBC API
A real life application needs to manipulate data stored
in a Database.
A database is a collection of related data in the form
of Tables. Most of the database uses SQL
(Structured Query Language) to Insert, Delete,
Update or retrieve stored records.
In order to connect a Java application (Front-End) to
a Database (Back-End) designed in MySQL,
Oracle, Sybase, MS SQL Server etc, you need a
Interface Driver Program.
Java Provides JDBC API (Java Database Connection Application Program Interface) and JDBC Driver
for MySQL to connect a MySQL database.
The Prerequisite for connecting a Java application to MySQL is adding MySQL
JDBC driver in the Project/Program.
The NetBeans IDE comes with pre-bundled MySQL JDBC Driver. You may add
JDBC Driver in the Database Connectivity Project as follows-
1. Open New or existing Project.
2. Right Click on
Libraries Node and
select Add Library..
4. Press
Add Library
Button
JDBC Driver
Communication with a Database using JDBC API & Driver
Classes used for Database Connectivity
The Core element of JDBC is JDBC API, which consists of a set of
Java classes equipped with predefined methods to handle
various data access functions such as Selecting appropriate
database driver, establishing connection, submitting SQL
query and processing results.
JDBC API offers four main classes, which are Driver Manager Class: It loads the JDBC driver to locate,
logs and access a database.
 Connection Class: It manages communication between Java
Client Application and Database, through SQL statements.
 Statement Class: It contains SQL commands which is
submitted to the Database Server and returns ResultSet
object containing the result of SQL statement.
 Result Set Class: It provides predefined mehods to access
and convert data values returned by the executed SQL
statement.
3. Select MySQL
JDBC Driver
Connecting MySQL from JAVA Application
After installing JDBC Driver, you may access MySQL
database through JAVA Application.
The Following Six steps may be followed to establish
a connection with MySQL database.
 Step 1: Import Required package/classes in the
application.
 Step 2: Register the JDBC Driver to JDBC Driver
Manager.
 Step 3: Open a Connection.
 Step 4: Execute a Query.
 Step 5: Extract data from Result set
 Step 6: Close Connection.
A JDBC driver must be registered with JDBC Driver Manage using Class.forName()
method before establishing a connection.
Visit "http://ip4you.blogspot.in" for more...
1
Chapter 6: Database Connectivity (XII-IP)
Working with Data Connectivity Project
Working with Data Connectivity Project
 Step 1: Importing Required package/classes
Step 3: Opening a Connection
To Import Java.sql Library package in the Application you need
to give following import statements.
DriverManager.getConnection() method is used to create a
connection object that represents a physical connection
with database. It requires the complete address/path of
the database (Database URL), user name and
password as a parameter. A database URL can be
formed as- jdbc:mysql :// localhost/ <database name>
Suppose school is a database designed in MySQL, then
Database URL will be as follows“jdbc:mysql://localhost/school”
You can assign this string on a variable, which can be used
later with DriverManager.getConnection() method.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
Or
import java.sql.*;
import java.sql.ResultSet;
 Step 2: Registering the JDBC Driver
To open a Communication channel, you require to initialize driver
by registering the JDBC driver with JDBC Driver Manager using
Class.forName() method of java.lang package.
Class.forName(“java.sql.DriverManager”);
String DB_URL = “jdbc:mysql://localhost/school”;
Connection con = DriverManager.getConnection(DB_URL,”root”, ”abc”)
Working with Data Connectivity Project
Working with Data Connectivity Project
Step 4: Executing a Query
Step 5: Extracting Data from ResultSet object
You must create a Statement object for building and submitting a
SQL query, using CreateStatement() method of Connection
object created in Step 3.
To retrieve the data from the ResultSet object, which contains
records, You may use the following method.
Statement stmt = con.createStatement();
To execute a query executeQuery() method along with a valid
SQL statement is used, which returns the records from the
database (Result Set) on ResultSet type object.
ResultSet rs = stmt.executeQuery(“<SQL Query>”);
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(“select roll,name,class from student”);
Result Set refers to a logical set of records from the database.
An executeUpdate() method is used in place of executeQuery() for Insert,
Delete or Update SQL command.
Working with Data Connectivity Project
Since a ResultSet object may contain more than one records
(when SQL query may return multiple records) , so a loop is
required to process all the records. A while… loop is generally
used to read all records.
To break a loop <ResultSet object>.next() method is used,
which returns false when all the records have been read from
the Result set.
int r,c ;
You can use jTextArea or jTable
String n;
swing controls to display
while (rs.next())
multiple records instead of
{ r= rs.getInt(“roll”);
jTextField.
n= rs.getString(“name”);
c= rs.getInt(“class”);
// statements to display variables on Multi-line display controls //
……………………………………………..
}
Visit "http://ip4you.blogspot.in" for more...
<ResultSet object>.get<type>(<column name/number>);
Where <type> may be Int, Long, String, Float etc. depending
on the type of column the table.
Generally, the data values are assigned on the variables and later used in
the TextField controls of the Form using setText() method.
int r= rs.getInt(“roll”);
int r= rs.getInt(1);
String n= rs.getString(“name”);
String n= rs.getString(2);
int c= rs.getInt(“class”);
int c= rs.getInt(3);
The variable can be used to display the
values in the Text boxes like thisjTextField1.setText(“”+r);
You can use Column
number instead of column
name of the table
Working with Data Connectivity Project
Step 6: Closing connection
After all the processing , the final step is to
close the environment by closing ResultSet,
Statement and Connection objects using
close() method.
rs.close();
stmt.close();
con.close();
To handle errors during establishing connection all the
required statements are kept in a try{…} catch (){…} block
like this–
try{……………………
<Data connectivity statements……..>
}
catch ( Exception <variable>)
{
<error statement>;
}
2
Chapter 6: Database Connectivity (XII-IP)
A Sample Code for Database Connectivity
import java.sql.*;
// 1. import package at the top//
/* The following code may be placed in ActionPerformed event of a button*/
String db=“jdbc:mysql://loacalhost/school”);
// Database URL
String qr= “select roll, name, class from student”; // Query
try{
Class.forName(“java.sql.DriverManager”);
//2. Register Driver
Connection con=Driver.getConnection(db, ”root”, ”xyz”); //3.Open Connection
Statement stmt=con.createStatement();
// 4. Execute Query
ResultSet rs= stmt.executeQuery( qr);
int r, c;
String n;
while (rs.next())
// 5. Extract Data//
{ r= rs.getInt(“roll”);
n= rs.getString(“name”);
c= rs.getInt(“class”);
……………………………….; // Code to manipulate data//
}
rs.close();
//6.Close Environment//
stmt.close();
con.close();
}
catch (Exception e)
{ JOptionPane.showMessageDialog(null, e.getMessage()); }
Commonly used ResultSet Methods
A Result set object maintains a cursor, which points to its current row of
data. When it is created, cursor is positioned before the first row. You
can move the cursor using the following methods.
Method
Purpose
next ()
Moves the cursor forward one row. It returns false when cursor is
positioned after the last record.
previous()
Moves cursor to previous record from current position. It returns
false when cursor is positioned before the first record.
first()
Moves cursor to first record. It returns true if it positioned at first
record otherwise returns false.
last()
Moves cursor to last record. It returns true if it positioned at last
record otherwise returns false.
relative(n)
Moves cursor relative to its current position i.e if it is on 2nd row,
then relative(3) places cursor at 5th record.
absolute(n)
Moves cursor at nth record of result set irrespective to its current
position.
getRow()
Returns the current row number where cursor is positioned.
Example 1:
Search & Display Record using Text Fields
Example 1:
Design of the Table
Objective :
It is assumed that a database and table is designed in MySQL and some
Consider the following design of a database application to Search
and display a record as per given Mobile number from the
Teacher table containing Name, Subject and Mobile Number
column.
records are present. However, if database and tables are not available
then follow the following steps for creating database & tables in MySQL.
Step 1: Open MySQL and give password to login.
Step 2: Type the following MySQL commands.
Assumption
Database : School
Table : Teacher
Column/Field & Type
•Name Character (40)
•Subject Varchar(30)
•Mobile Char(12)
With some records.
mysql> create database school;
mysql> use school;
mysql> create table teacher
->(name char(40), subject varchar(30), mobile char(12));
mysql> insert into teacher values (‘Ramesh’, ’Biology’, ’9998123444’);
mysql> insert into teacher values (‘Ajay’, ’Physics’, ’9899123322’);
mysql> insert into teacher values (‘Naveen’, ’Maths’, ’9412335454’);
MySQL
User Name: root
Password: kvuc
Kindly note that Mobile Number of teachers should be different
to facilitate unique search/match of the record.
Example 1:
Coding of Event in NetBeans
Example 1:
Design of Application in NetBeans
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
Design
Form
Add
MySQL
JDBC
Driver
Add
Swing
Controls
// TODO code for Display Record Button:
String DB="jdbc:mysql://localhost/school";
//Database URL
String name, sub, mob;
mob=jTextField3.getText();
String qr= "select name, subject, mobile from teacher where mobile='"+mob+"';";
try{
Class.forName("java.sql.DriverManager");
Connection con= DriverManager.getConnection(DB,"root","kvuc");
Statement stmt= con.createStatement();
ResultSet rs= stmt.executeQuery(qr);
if(rs.next())
// if record found extract & display
{ name = rs.getString("Name");
sub = rs.getString("subject");
jTextField1.setText(name);
jTextField2.setText(sub);
con.close(); stmt.close(); rs.close(); // close connection
}
else
// if record not found, Display Error in a dialog
JOptionPane.showMessageDialog(null, "Mobile Number Not Found");
}
catch(Exception e)
{ JOptionPane.showMessageDialog(null,e.getMessage());} }
Visit "http://ip4you.blogspot.in" for more...
3
Chapter 6: Database Connectivity (XII-IP)
Example 2:
Entry of records in a table using a Form
Example 2:
Design of Entry Form in NetBeans
Objective :
Consider the following design of a database application to Enter
records in the Teacher table containing Name, Subject and
Mobile Number column.
Assumption
Database : School
Table : Teacher
Column/Field & Type
•Name Character (40)
•Subject Varchar(30)
•Mobile Char(12)
With some records.
Design
Form
Add
MySQL
JDBC
Driver
Add
Swing
Controls
MySQL
User Name: root
Password: kvuc
Example 2:
Coding of Event in NetBeans
jTable Swing Control
Sometimes it is required to represent information in tabular form.
Java provides JTable swing control to handle multiple records
retrieved from the database. A table consists of certain rows and
columns.
Table
Roll
Name
Marks
Grade
1
Amit
80
B
2
Ajay
90
A
Cell
A table model works behind JTable control which contains source data for
JTable. Java provides multiple Table model, but DefaultTableModel is
commonly used.
 Properties & Methods of JTable control:
Method
Description
int getColumnCount()
Returns the number of column in the table
int getRowCount()
Returns the number of rows in the table
Object getValueAt(row,col)
Returns value of given row & column of the table
The most commonly used properties are Font, Foreground and Enabled etc.
Designing a Simple Table
Designing a Simple Table
1. Create an application and attach a JFrame (Form).
2. Attach Table
control to the
frame
Visit "http://ip4you.blogspot.in" for more...
3. Right click on the
Table control and select
Table Contents..
4
Chapter 6: Database Connectivity (XII-IP)
Designing a Simple Table
Designing a Simple Table
5. Select
Row tab
3. Select
Column tab
6. Set Count as 0
4. Rename all column
Titles like Roll, Name,
Marks and Grade etc.
Now attach Button controls on the Form and write TODO code in
ActionPerformed event for the specific functionality.
Working with jTable
 Insert the following import statement at the beginning.
import javax.swing.table.*;
 Obtain table’s model in a DefaultTableModel object as per the
following (Suppose tm is an identifier and jTable1 is table)DefaultTableModel tm=(DefaultTableModel) jTable1.getModel();
 Adding Rows
1. Create an object array and put values (directly or using TextFields) in
the order in which jTable is designed.
object myrow[ ]= {5, “Mukesh Kumar”,60,”B”};
object myrow[ ]= {jTextField1.getText(), jTextField2.getText(),
jTextField3.getText(), jTextField4.getText()};
2. Add object array in TableModel by using addrow() method.
tm.addRow(myrow);
 Deleting Rows
To delete a row, you may call removeRow() method with row number
to be deleted.
tm.removerow(2);
Example 3:
Designing Frame with jTable
Visit "http://ip4you.blogspot.in" for more...
Example 3:
Displaying Records in jTable Control
Let us design an Application as per the following screen shot.
We assume that a Database named School containing a
Student (Roll, Name, Class) table with some test records has
been created already in MySQL.
A Simple Database Application using Table
TblStu [Jtable]
BtnDisp [Jbutton]
BtnExit [Jbutton]
Example 3:
Coding Event for the jTable & Database Connectivity
5
Chapter 6: Database Connectivity (XII-IP)
Example 4:
Navigating Records in Text Fields
Example 4:
Design of Application in NetBeans
Let us Redesign design the Previous Application as per the following
screen shot using Text Fields and Navigation Buttons.
We assume the same Database named School containing a Student
(Roll, Name, Class) table with some test records has been created
already in MySQL.
JTextField (s) as
TxtRoll, TxtName &
TxtClass
Ensure the
JDBC driver
is present in
the library
JButtons as
BtnFirst, BtnPrev, BtnNext,
BtnLast & BtnExit
Example 4:
Coding of events in NetBeans
Object are
globally
declared, so
that they can
be access in
all methods.
Connection is
established
and cursor is
placed on first
record when
Frame loads.
Example 4:
Coding of events in NetBeans
Coding for
NEXT button
to locate and
display next
record.
The following Swing Controls are
attached ( Name and Types)
Example 4:
Coding of events in NetBeans
Coding for
FIRST
button to
locate and
display first
record.
Coding for
PREVIOUS
button to
locate and
display
previous
record from
current
position.
Example 4:
Coding of events in NetBeans
Coding for
EXIT button
to close
connection
environment
and Exit
from
application.
Coding for
LAST button to
locate and
display last
record
Visit "http://ip4you.blogspot.in" for more...
6