JDBC
JDBC
POONAM DHAND
ASSISTANT PROFESSOR
COMPUTER SCIENCE DEPT.
GOVT. COLLEGE FOR GIRLS,LUDHIANA
JDBC – AN INTRODUCTION
JDBC stands for Java Database Connectivity. JDBC can also be defined as the
platform-independent interface between a relational database and Java
programming. JDBC is an Application Programming Interface (API) used to connect
Java application and execute the query with the database. JDBC allows for
accessing any form of tabular data from any source and can interact with various
types of Databases such as Oracle, MS Access, My SQL and SQL Server. It allows
java program to execute SQL statement and retrieve result from database.
FIG 1.1 describes the connection of the JDBC with the Database. JDBC API is
used to access tabular data stored in any relational database. JDBC provides a
complete set of interfaces that allows for portable access to an underlying
database. Java can be used to write different types of executables, such as Java
Applications, Java Applets, Java Servlets, Java Server Pages (JSPs), Enterprise
JavaBeans (EJBs). These different executables are able to use a JDBC driver to
access a database, and also used to store data. By the help of JDBC API, we can
save, update, delete and fetch data from the database. It is like Open Database
Connectivity (ODBC) provided by Microsoft, allowing Java programs to contain
database-independent code.
Components of JDBC
JDBC includes following components:
JDBC API: JDBC API provides access to relational data from the Java
programming language and can execute SQL statements, retrieve results,
and propagate changes back to an underlying data source . The JDBC API
uses two packages java.sql and javax.sql.
JDBC Drivers
JDBC drivers enable you to open database connections and to interact with it by
sending SQL or database commands then receiving results with Java. The following
are the different types of driver available in JDBC.
There are various steps which are used to connect any java application with the
database using JDBC. These steps are given below:
Establishing the Connection
Register the Driver class
Create connection
Create statement
Execute queries
Process the ResultSet Object
Close connection
The First step of connectivity is to establish a connection with the data source you
want to use. A data source can be a DBMS, a valid file system, or some other
source of data with a corresponding JDBC driver. JDBC applications connect to a
data source using the DriverManager class.
DriverManager Class
The DriverManager class acts as an interface between user application and drivers.
DriverManager class connects an application to a data source, which is specified by
a database URL. This class is used for establishing a connection between a
database and the appropriate driver and also keeps track of the drivers that are
available in the system. The DriverManager class maintains a list of Driver classes
that have registered themselves by calling the method
DriverManager.registerDriver(). Various methods of DriverManager Class are
given below
public static Connection getConnection(String url): is used to establish the
connection with the specified url.
public static Connection getConnection(String url,String userName,String
password): This method is used to establish the connection with the
specified url, username and password.
public static void registerDriver(Driver driver): This method is used to
register the given driver with DriverManager.
public static void deregisterDriver(Driver driver): This method is used to
deregister the given driver (drop the driver from the list) with
DriverManager.
java.sql.DriverManager class should be import to use these above
mentioned database connection methods
Registering the driver is the process by which the driver's class file is loaded
into the memory. . You must register the driver in your program before you
use it.So it can be utilized as an implementation of the JDBC interfaces. You
need to do this registration only once in your program. You can register a
driver in one of two ways.
Class.forName()
Example
a) Class.forName("sun.jdbc.odbc.JdbcOdbcDriver")
// For Registering JdbcOdbcDriver driver Class.
b) Class.forName("oracle.jdbc.driver.OracleDriver");
// For Registering OracleDriver driver Class.
DriverManager.registerDriver()
The second approach you can use to register a driver, is to use the static
DriverManager.registerDriver() method. The DriverManager class maintains a
list of Driver classes that have registered themselves by calling the method
DriverManager.registerDriver().
Example
Driver myDriver = new oracle.jdbc.driver.OracleDriver();
DriverManager.registerDriver( myDriver );
Creating Connection
After you've loading and Registering the driver class , you can establish a
connection using the DriverManager.getConnection() method.
Example:
Import java.sql;
Connection Con;
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con = DriverManager.getConnection(jdbc:odbc: url);
Connection Interface
Once the connection has been established you can interact with the database. A
Statement is an interface that represents a SQL statement. It provides methods to
execute queries with the database. You can execute Statement objects, and they
generate ResultSet objects. ResultSet is a table of data representing a database
result set. You need a Connection object to create a Statement object.
CallableStatement:
java.sql.CallableStatement is used to execute the stored procedures that
may contain both input and output parameters. Three types of parameters
exist: IN, OUT, and INOUT. The PreparedStatement object only uses the IN
parameter. Before calling the stored procedure, you must register OUT
parameters using registerOutParameter() method of CallableStatement.
Connection.prepareCall() method is used to instantiate a
CallableStatement object.
Example
CallableStatement stmt=con.prepareCall(“ Call Procedure1(?,?,?)”);
stmt.execute ();
RESULTSET INTERFACE
A table of data representing a database result set, which is usually generated by
executing a statement that queries the database. The result of the query after
execution of database statement is returned as table of data according to rows and
columns and this data is accessed using the ResultSet interface. The
java.sql.ResultSet interface represents the result set of a database query. A
ResultSet object maintains a cursor that points to the current row in the result set.
The term "result set" refers to the row and column data contained in a ResultSet
object.A default ResultSet object is not updatable and the cursor moves only in
forward direction.
Types of ResultSet Interface
ResultSet.TYPE_FORWARD_ONLY: The ResultSet can only be navigating
forward.
ResultSet.TYPE_SCROLL_INSENSITIVE: The ResultSet can be navigated
both in forward and backward direction. It can also jump from current
position to another position. The ResultSet is not sensitive to change made
by others.
ResultSet.TYPE_SCROLL_SENSITIVE : The ResultSet can be navigated in
both forward and backward direction. It can also jump from current position
to another position. The ResultSet is sensitive to change made by others to the
database.
A Statement object sends SQL statements to a database. There are three kinds of
Statement objects. Each is specialized to send a particular type of SQL statement:
A Statement object is used to execute a simple SQL statement with
noparameters
A PreparedStatement object is used to execute a pre-compiled SQL
statement with or without IN parameters.
A CallableStatement object is used to execute a call to a database stored
procedure.
You must construct a Statement object before executing an SQL statement. The
Statement object offers a way to send a SQL statement to the server (and gain
access to the result set). Each Statement object belongs to a Connection; use the
createStatement() method to ask the Connection to create the Statement object and
executeUpdate(), executeQuery() is used for execution.
To Connect the JDBC and ODBC we should have a database. Then we would be
required to create a DSN to use JDBC ODBC Bridge driver. The DSN (Data Source
Name) specifies the connection of an ODBC to a specific server. As its name JDBC-
ODBC bridge, it acts like a bridge between the Java Programming Language and
the ODBC to use the JDBC API. To use the JDBC API with the existing ODBC Sun
Microsystems (Now Oracle Corporation) provides the driver named
JdbcOdbcDriver. Full name of this class is sun.jdbc.odbc.JdbcOdbcDriver.
Go to the tab System DSN in the ODBC Data Source Administrator dialog
box then, Click on Add button select MS Access Driver (*.mdb) OR MS
Access Driver (*.accdb, *.mdb) -> click on Finish button.
In the next step a dialog box ODBC Microsoft Access Setup will be opened
then provide the field's values corresponding to the field's label (i.e. provide
the DSN name as you wish) and then click on the "Select" button.
In the next step a new dialog box "Select database" will be opened.
Here you have to select the directory where you have stored your file and
provide the name in the place of the Database Name and then press ok
Ok.
There are following steps to create the database connection with Java application:
For example:
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver")
or
Class.forName("oracle.jdbc.odbc.JdbcOdbcDriver");
Import java.sql;
Connection Con;
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con = DriverManager.getConnection(jdbc:odbc: url);//here url is dsn which
is created by user
Example:
Statement stmt = con.createStatement();
5) Execute SQL Queries
The Statement interface provides the executeQuery( ) , executeUpdate() and
execute ()method to execute SQL statements.
Example
ResultSet rs = stmt.executeQuery("select * from students");
while (rs.next())
{
System.out.println (rs.getInt(1)+" "+rs.getString(2)+" "+rs.getFloat(3));
}
6) Closing the Connection
The Connection interface provides close( ) method, used to close the connection.
It is invoked to release the session after execution of SQL statement.
Syntax:
public void close( ) throws SQLException
Example:
con.close( );
import java.lang.*;
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.sql.*;
import java.util.*;
public class Emp_Record t extends JFrame implements ActionListener
{
String url,sql,eno,dept,empname,fname,doav,sqlI,sqlU;
String[] rwData;
int response,stmtval,rwcnt,rec,coln,flag,reply,nrows;
Vector dataRows;
Font fnt,head;
JButton jbtnaddrec;
JButton jbtndel;
JButton jbtnupdate;
JButton jbtnview;
JButton jbtnfirst;
JButton jbtnprev;
JButton jbtnnext;
JButton jbtnlast;
JButton jbtnsave;
JButton jbtnexit;
JLabel jlblfrmhead;
JLabel lbleno;
JLabel lbldept;
JLabel lblname;
JLabel lblfname;
JTextField jtxteno;
JTextField jtxtdept;
JTextField jtxtname;
JTextField jtxtfname;
Connection conn;
Statement stmt;
ResultSet rs;
Container container;
jbtnaddrec.setMnemonic('I');
jbtnaddrec.setToolTipText("Adds a new Record to the table");
jbtnupdate.setMnemonic('U');
jbtnupdate.setToolTipText("Update a record in the table");
jbtndel.setMnemonic('D');
jbtndel.setToolTipText("Delete an Existing Record from the table");
jbtnview.setMnemonic('V');
jbtnview.setToolTipText("TO view the records in the table");
jbtnfirst.setMnemonic('F');
jbtnfirst.setToolTipText("To view the first record in the table");
jbtnprev.setMnemonic('P');
jbtnprev.setToolTipText("To view the Previous record");
jbtnnext.setMnemonic('N');
jbtnnext.setToolTipText("To view the next record ");
jbtnlast.setMnemonic('L');
jbtnlast.setToolTipText("To view the Last record in the table");
jbtnsave.setMnemonic('S');
jbtnsave.setToolTipText("Save records");
jbtnexit.setMnemonic('X');
jbtnexit.setToolTipText("Exit Application");
jtxteno=new JTextField(10);
jtxtdept = new JTextField(20);
jtxtname = new JTextField(15);
jtxtfname = new JTextField(15);
jbtnaddrec.addActionListener(this);
jbtndel.addActionListener(this);
jbtnupdate.addActionListener(this);
jbtnview.addActionListener(this);
jbtnfirst.addActionListener(this);
jbtnprev.addActionListener(this);
jbtnnext.addActionListener(this);
jbtnlast.addActionListener(this);
jbtnsave.addActionListener(this);
jbtnexit.addActionListener(this);
container.setLayout(null);
fnt = new Font("TIMES NEW ROMAN",Font.BOLD,15);
jbtnaddrec.setFont(fnt);
jbtndel.setFont(fnt);
jbtnupdate.setFont(fnt);
jbtnview.setFont(fnt);
jbtnfirst.setFont(fnt);
jbtnprev.setFont(fnt);
jbtnnext.setFont(fnt);
jbtnlast.setFont(fnt);
jbtnsave.setFont(fnt);
jbtnexit.setFont(fnt);
lbleno.setFont(fnt);
lbldept.setFont(fnt);
lblname.setFont(fnt);
lblfname.setFont(fnt);
jbtnaddrec.setBounds(450,80,75,25);
container.add(jbtnaddrec);
jbtnupdate.setBounds(540,80,75,25);
container.add(jbtnupdate);
jbtndel.setBounds(630,80,75,25);
container.add(jbtndel);
jbtnview.setBounds(720,80,75,25);
container.add(jbtnview);
jbtnfirst.setBounds(450,120,75,25);
container.add(jbtnfirst);
jbtnprev.setBounds(540,120,75,25);
container.add(jbtnprev);
jbtnnext.setBounds(630,120,75,25);
container.add(jbtnnext);
jbtnlast.setBounds(720,120,75,25);
container.add(jbtnlast);
lbleno.setBounds(420,220,100,25);
container.add(lbleno);
jtxteno.setBounds(560,220,100,25);
container.add(jtxteno);
lbldept.setBounds(420,255,100,25);
container.add(lbldept);
jtxtdept.setBounds(560,255,100,25);
jtxtdept.setToolTipText("Department");
container.add(jtxtdept);
lblname.setBounds(420,290,100,25);
container.add(lblname);
jtxtname.setBounds(560,290,100,25);
jtxtname.setToolTipText("Employee name");
container.add(jtxtname);
lblfname.setBounds(420,325,100,25);
container.add(lblfname);
jtxtfname.setBounds(560,325,100,25);
jtxtfname.setToolTipText("Father's name");
container.add(jtxtfname);
jbtnsave.setBounds(420,400,75,25);
container.add(jbtnsave);
jbtnexit.setBounds(560,400,75,25);
container.add(jbtnexit);
setSize(1300,1300);
show();
connection();
System.out.println("\n Connection Called");
setResizable(false);
}
try
{
url="jdbc:odbc:java1";
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
conn = DriverManager.getConnection(url);
stmt=conn.createStatement();
System.out.println("Successfully Connected!!!");
disableBtns();
jbtnsave.setEnabled(false);
disableFlds();
}
catch(SQLException sqlExcep)
{
System.out.println("ERROR:" +sqlExcep);
}
catch(ClassNotFoundException clsntExcp)
{
System.out.println("ERROR:" +clsntExcp);
}
}
try
{
rs = stmt.executeQuery(sql);
while(rs.next())
{
JOptionPane.showMessageDialog(null,"Record Exists!!!","Note",2);
disableFlds();
return;
}
enableFlds();
clsAllFlds();
jtxteno.setText(eno);
jtxtdept.requestFocus();
}
catch(SQLException sqlexcep)
{
System.out.println("ERROR:"+sqlexcep);
}
}
catch(NullPointerException nullPntrExcep)
{
return;
}
}
popFlds();
}
//Method for viewing previous record
public void prevRcrd()
{
rec=rec-1;
disableFlds();
enableBtns();
if (rec >= 0)
{
if (rec==0)
{
jbtnprev.setEnabled(false);
jbtnfirst.setEnabled(false);
}
eno= ((String []) (dataRows.elementAt (rec))) [0];
dept = ((String []) (dataRows.elementAt (rec))) [1];
empname= ((String []) (dataRows.elementAt (rec))) [2];
fname = ((String []) (dataRows.elementAt (rec))) [3];
}
popFlds();
}
}
popFlds();
}
// Method for insert and update the record after clicking the save button
public void applyRcrd()
{
getProdVal(); //.....................................
if(eno.length() == 0)
{
JOptionPane.showMessageDialog(null,"Employee id Cannot Be
Blank !!!","Note",2);
jtxteno.requestFocus();
return;
}
if (dept.length() == 0)
{
JOptionPane.showMessageDialog(null,"Department Cannot Be
Blank !!!","Note",2);
jtxtdept.requestFocus();
return;
}
if (empname.length() == 0)
{
JOptionPane.showMessageDialog(null,"Name Cannot be left blank !!!","Note",2);
jtxtname.requestFocus();
return;
}
else
{
for(int i=0;i<empname.length();i++)
{
if(Character.isDigit(empname.charAt(i)))
{
JOptionPane.showMessageDialog(null,"Enter Characters Only in Name
Field !!!","Note",2);
jtxtname.requestFocus();
return;
}
}
}
if (fname.length() == 0)
{
JOptionPane.showMessageDialog(null," Father's Name field cannot be
blank !!!","Note",2);
jtxtfname.requestFocus();
return;
}
else
{
for(int i=0;i<fname.length();i++)
{
if(Character.isDigit(fname.charAt(i)))
{
JOptionPane.showMessageDialog(null,"Enter Characters Only in Father's Name
Field!!!","Note",2);
jtxtfname.requestFocus();
return;
}
}
}
String sqlU = "UPDATE EMP_INFO " + "SET EMPNO= '"+eno+"', DEPT= '"+dept+"',
ENAME='"+empname+"', FATHERNAME = '"+fname+"' WHERE EMPNO='"+eno+"'" ;
try
{
enableBtns();
if ( flag == 1 )
{
reply = JOptionPane.showConfirmDialog(null, "Insert Changes ??");
if (reply ==JOptionPane.YES_OPTION)
{
nrows = stmt.executeUpdate(sqlI);
JOptionPane.showConfirmDialog(null,"Changes Saved !! want to
Continue !!!","Note",2);
if(reply==JOptionPane.YES_OPTION)
{ clsAllFlds();
}
else
{
clsAllFlds();
}
}
if (reply == JOptionPane.NO_OPTION)
{
return;
}
jbtnview.setEnabled(true);
disableFlds();
}
if(flag == 2)
{
reply = JOptionPane.showConfirmDialog(null,"Save Changes ??");
if(reply == JOptionPane.YES_OPTION)
{
getProdVal();
nrows = stmt.executeUpdate(sqlU);
JOptionPane.showMessageDialog(null,"Changes Saved !! Press the view button
to refresh the Records!!!","Note",2);
clsAllFlds();
}
if(reply == JOptionPane.NO_OPTION)
{
return;
}
jbtnview.setEnabled(true);
disableFlds();
jbtnsave.setEnabled(false);
}
}
catch(SQLException sqlExcep)
{
System.out.println("Error "+ sqlExcep);
}
}
}
public static void main(String args[])
{
Emp_Record ER= new Emp_Record ();
WindowListener l1=new WindowAdapter()
{
public void windowClosing(WindowEvent winEvt)
{System.exit(0);}
};
ER.addWindowListener(l1);
}
}
Output Screens
QUESTIONS
SHORT ANSWER QUESTIONS
Q1. Define JDBC.
Ans: JDBC stands for Java Database Connectivity. JDBC can also be defined as
the platform-independent interface between a relational database and Java
programming. JDBC is an Application Programming Interface (API) used to
connect Java application and execute the query with the database. JDBC
allows for accessing any form of tabular data from any source and can
interact with various types of Databases such as Oracle, MS Access, My SQL
and SQL Server. It allows java program to execute SQL statement and retrieve
result from database.
Q2. Define DriverManager.
Ans: The JDBC DriverManager class manages various drivers which defines
objects that connect Java applications to a JDBC driver. javax.naming and
javax.sql packages are used to register a DataSource object and establish a
connection with a data source.
EXERCISE
Q1. What is JDBC? Explain various steps to create a database connection?
Q2. Create a Hotel Management Application using JDBC .
Q3. Explain the following:
a) Components of JDBC
b) Driver Types
c) DriverManager Class