Java Database Connectivity
What is JDBC?
JDBC stands for Java Database Connectivity, which is a standard Java API (Application
Program Interface) for database-independent connectivity between the Java programming
language and a wide range of databases.
The JDBC library includes APIs for each of the tasks commonly associated with database usage:
• Making a connection to a database
• Creating SQL or MySQL statements
• Executing that SQL or MySQL queries in the database
• Viewing & Modifying the resulting records
Fundamentally, JDBC is a specification that 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 ServerPages (JSPs)
All of these different executables are able to use a JDBC driver to access a database and take
advantage of the stored data.
JDBC provides the same capabilities as ODBC, allowing Java programs to contain database-
independent code.
JDBC Architecture:
The JDBC API supports both two-tier and three-tier processing models for database access but in
general JDBC Architecture consists of two layers:
• JDBC API: This provides the application-to-JDBC Manager connection.
• JDBC Driver API: This supports the JDBC Manager-to-Driver Connection.
The JDBC API uses a driver manager and database-specific drivers to provide transparent
connectivity to heterogeneous databases.
The JDBC driver manager ensures that the correct driver is used to access each data source. The
driver manager is capable of supporting multiple concurrent drivers connected to multiple
heterogeneous databases.
Following is the architectural diagram, which shows the location of the driver manager with
respect to the JDBC drivers and the Java application:
Common JDBC Components:
The JDBC API provides the following interfaces and classes:
• DriverManager: This class manages a list of database drivers. Matches connection
requests from the java application with the proper database driver using communication
subprotocol.
• Driver: This interface handles the communications with the database server.
• Connection: This interface with all methods for contacting a database. The connection
object represents communication context, i.e., all communication with database is
through connection object only.
• Statement: You use objects created from this interface to submit the SQL statements to
the database. Some derived interfaces accept parameters in addition to executing stored
procedures.
• ResultSet: These objects hold data retrieved from a database after you execute SQL
query using Statement objects. It acts as temporary table that allow you to move through
its data.
• SQLException: This class handles any errors that occur in a database application.
What is JDBC Driver?
JDBC drivers implement the defined interfaces in the JDBC API for interacting with your
database server.
For example, using 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 [Link] package that ships with JDK contains various classes with their behaviors defined
and their actual implementations are done in third-party drivers. Third party vendors implement
the [Link] interface in their database driver.
JDBC Drivers Types:
JDBC driver implementations vary because of the wide variety of operating systems and
hardware platforms in which Java operates. Sun has divided the implementation types into four
categories, Types 1, 2, 3, and 4, which are explained below:
Type 1: JDBC-ODBC Bridge Driver:
In a Type 1 driver, a JDBC bridge is used to access ODBC drivers installed on each client
machine. Using ODBC requires configuring on your system a Data Source Name (DSN) that
represents the target database.
When Java first came out, this was a useful driver because most databases only supported ODBC
access but now this type of driver is recommended only for experimental use or when no other
alternative is available.
The JDBC-ODBC bridge that comes with JDK 1.2 is a good example of this kind of driver.
Type 2: JDBC-Native API:
In a Type 2 driver, JDBC API calls are converted into native C/C++ API calls which are unique
to the database. These drivers typically provided by the database vendors and used in the same
manner as the JDBC-ODBC Bridge, the vendor-specific driver must be installed on each client
machine.
If we change the Database we have to change the native API as it is specific to a database and
they are mostly obsolete now but you may realize some speed increase with a Type 2 driver,
because it eliminates ODBC's overhead.
The Oracle Call Interface (OCI) driver is an example of a Type 2 driver.
Type 3: JDBC-Net pure Java:
In a Type 3 driver, a three-tier approach is used to accessing databases. The JDBC clients use
standard network sockets to communicate with a middleware application server. The socket
information is then translated by the middleware application server into the call format required
by the DBMS, and forwarded to the database server.
You can think of the application server as a JDBC "proxy," meaning that it makes calls for the
client application. As a result, you need some knowledge of the application server's configuration
in order to effectively use this driver type.
Your application server might use a Type 1, 2, or 4 driver to communicate with the database,
understanding the nuances will prove helpful.
Type 4: 100% pure Java:
A Type 4 driver is a pure Java-based driver that communicates directly with vendor's database
through socket connection. This is the highest performance driver available for the database and
is usually provided by the vendor itself.
This kind of driver is extremely flexible; you don't need to install special software on the client
or server. Further, these drivers can be downloaded dynamically.
Oracle thin driver and MySQL's Connector/J driver is a Type 4 driver. Because of the
proprietary nature of their network protocols, database vendors usually supply type 4 drivers.
JDBC Database Connections
After you've installed the appropriate driver, it's time to establish a database connection using
JDBC.
The programming involved to establish a JDBC connection is fairly simple. Here are these
simple four steps:
• Import JDBC Packages: Add import statements to your Java program to import
required classes in your Java code.
• Register JDBC Driver: This step causes the JVM to load the desired driver
implementation into memory so it can fulfill your JDBC requests.
• Database URL Formulation: This is to create a properly formatted address that points
to the database to which you wish to connect.
• Create Connection Object: Finally, code a call to the DriverManager object's
getConnection( ) method to establish actual database connection.
Import JDBC Packages:
The Import statements tell the Java compiler where to find the classes you reference in your
code and are placed at the very beginning of your source code.
To use the standard JDBC package, which allows you to select, insert, update, and delete data in
SQL tables, add the following imports to your source code:
import [Link].* ; // for standard JDBC programs
import [Link].* ; // for BigDecimal and BigInteger support
Register JDBC Driver:
You must register your driver in your program before you use it. Registering the driver is the
process by which the Oracle driver's class file is loaded into memory so it can be utilized as an
implementation of the JDBC interfaces.
You need to do this registration only once in your program.
You should use the registerDriver() method if you are using a non-JDK compliant JVM, such as
the one provided by Microsoft.
The following example uses registerDriver() to register the Oracle driver:
try {
Driver myDriver = new [Link]();
[Link]( myDriver );
}
catch(ClassNotFoundException ex) {
[Link]("Error: unable to load driver class!");
[Link](1);
}
Database URL Formulation:
After you've loaded the driver, you can establish a connection using the
[Link]() method.
getConnection(String url, String user, String password)
Here each form requires a database URL. A database URL is an address that points to your
database.
Formulating a database URL is where most of the problems associated with establishing a
connection occur.
Following table lists down popular JDBC driver names and database URL.
RDBMS JDBC driver name URL format
MySQL [Link] jdbc:mysql://hostname/ databaseName
jdbc:oracle:thin:@hostname:port
ORACLE [Link]
Number:databaseName
DB2 [Link].DB2Driver j[Link]hostname:port Number/databaseName
jdbc:sybase:Tds:hostname: port
Sybase [Link]
Number/databaseName
All the highlighted part in URL format is static and you need to change only remaining part as
per your database setup.
Create Connection Object:
Using a database URL with a username and password:
[Link]() method used to create a connection object. It requires you to
pass a database URL, a username, and a password.
Assuming you are using Oracle's thin driver, you'll specify a host:port:databaseName value for
the database portion of the URL.
If you have a host at TCP/IP address [Link]/localhost with a host name of dmu, and your
Oracle listener is configured to listen on port 1521, and your database name is EMP, then
complete database URL would then be:
jdbc:oracle:thin:@dmu:1521:EMP
Now you have to call getConnection() method with appropriate username and password to get a
Connection object as follows:
String URL = "jdbc:oracle:thin:@dmu:1521:EMP";
String USER = "username";
String PASS = "password"
Connection conn = [Link](URL, USER, PASS);
Closing JDBC connections:
At the end of your JDBC program, it is required explicitly close all the connections to the
database to end each database session. However, if you forget, Java's garbage collector will close
the connection when it cleans up stale/old objects.
Relying on garbage collection, especially in database programming, is very poor programming
practice. You should make a habit of always closing the connection with the close() method
associated with connection object.
To ensure that a connection is closed, you could provide a finally block in your code. A finally
block always executes, regardless if an exception occurs or not.
To close above opened connection you should call close() method as follows:
[Link]();
Explicitly closing a connection conserves DBMS resources, which will make your database
administrator happy.
For a better understanding, see the following example
// Create database using the ff parameters database name: hrmdb, user name: hrmdb ,password:
hrmdbe and table name :emptable and design the following jframeform
//import package
import [Link].*;
public class Employee extends [Link] {
Connection con;
Statement stmt;
ResultSet rs;
/** Creates new form Employee */
public Employee() {
initComponents();
DoConnect(); // method declaration used to connect database
public void DoConnect(){
try
//STEP 2: Register JDBC driver
Driver myDriver = new [Link]();
[Link]( myDriver );
[Link]("Driver Loaded");
//SETP 3 :Open connection to database
con=[Link]("jdbc:oracle:thin:@localhost:1521:xe", "hrmdb", "hrmdb"); //type
4
stmt=[Link](ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);
// Step 4: Execute query
String sql="select * from emptable";
rs=[Link](sql);
// populate first record on the form
[Link]();
[Link]([Link]("eid"));
[Link]([Link]("ename"));
[Link]([Link]("efname"));
[Link]([Link]([Link]("eage")));
//to display on output windows
while ([Link]()) { //start at raw 2
String id=[Link](1);
String name=[Link](2);
[Link](id + " "+ name);
//Step 5: Close connection
// [Link]();
// [Link]();
// [Link]();
}catch(SQLException err){
[Link]([Link]());
//For First navigation button
try {
if(con!=null)
{ [Link]();
[Link]([Link]("eid"));
[Link]([Link]("ename"));
[Link]([Link]("efname"));
[Link]([Link]([Link]("eage")));
} catch(SQLException ex)
{ [Link](null,[Link]()); }
//for next navigation button
try {
if(con!=null)
[Link]();
[Link]([Link]("eid"));
[Link]([Link]("ename"));
[Link]([Link]("efname"));
[Link]([Link]([Link]("eage")));
} catch(SQLException ex)
[Link](null,[Link]());
//for previous navigation button
try {
if(con!=null)
{ [Link]();
[Link]([Link]("eid"));
[Link]([Link]("ename"));
[Link]([Link]("efname"));
[Link]([Link]([Link]("eage")));
} catch(SQLException ex)
{ [Link](null,[Link]()); }
//For Last navigation button
try {
if(con!=null)
{ [Link]();
[Link]([Link]("eid"));
[Link]([Link]("ename"));
[Link]([Link]("efname"));
[Link]([Link]([Link]("eage")));
} catch(SQLException ex)
[Link](null,[Link]());
//Save new data
try {
if(con!=null)
PreparedStatement pstmt=[Link]("insert into emptable values(?,?,?,?)");
String id1=[Link]();
String name=[Link]();
String fname=[Link]();
int age= [Link]([Link]());
[Link]();
[Link](1, id1);
[Link](2, name);
[Link](3, fname);
[Link](4, age);
[Link]();
[Link](null,"One row inserted");
} catch(SQLException ex)
[Link](null,[Link]());
//Delete record
String id1=[Link]();
try{
String sql = "DELETE FROM emptable WHERE eid=?";
PreparedStatement ps = [Link](sql);
[Link](1, id1);
int rowsDeleted = [Link]();
if (rowsDeleted > 0)
[Link]("A Record was deleted successfully!");
} catch (SQLException ex) {
[Link](null,[Link]());
//Search record by id
try{
String id1=[Link]();
String str="select * from emptable where eid='"+id1+"'";
rs= [Link](str);
[Link]();
[Link]([Link]("eid"));
[Link]([Link]("ename"));
[Link]([Link]("efname"));
[Link]([Link]([Link]("eage")));
[Link]("A Record is found successfully!");
} catch (SQLException ex) {
[Link](null,[Link]());
}
//update record
try{
String id=[Link]();
String name=[Link]();
String fname=[Link]();
int age= [Link]([Link]());
PreparedStatement ps=null;
String str="update emptable set ename=?,efname=?,eage=? where eid=?";
ps=[Link](str);
[Link](1, name);
[Link](2, fname);
[Link](3, age);
[Link](4, id);
[Link]();
[Link](null,"One row updated");
} catch (SQLException ex) {
[Link]([Link]()); }
}// end of employee class