Go4Expert (http://www.go4expert.com/)
-   Java (http://www.go4expert.com/articles/java-tutorials/)
-   -   JDBC Basics - Part I (http://www.go4expert.com/articles/jdbc-basics-part-i-t21213/)

techgeek.in 6Mar2010 00:43

JDBC Basics - Part I


JDBC is a platform-independent interface between relational databases and Java. In today's Java world, JDBC is a standard application programming interface (API) for accessing enterprise data in relational databases (such as Oracle, MySQL, Sybase, and DB2) using Structured Query Language (SQL). JDBC stands for Java Database Connectivity.

How Does JDBC Work?

  • Java code calls a JDBC library (using the java.sql and javx.sql packages).
  • JDBC loads a driver; for example, an Oracle driver is loaded using the following code snippet for example:
  • Calling Class.forName() automatically creates an instance of the driver and registers the driver with the DriverManager class.The driver talks to a particular database such as Oracle or MySQL.
  • DriverManager is a connection factory class. In fact, it is the only class that can create database connections. The DriverManager uses drivers to create connections.
  • A Java database application uses the DriverManager class to get the java.sql.Connection object, which represents a database connection.

Who Provides These JDBC Drivers?

Usually, a database vendor (such as MySQL, Oracle, Sybase, and so on) writes a JDBC driver (a specific software for a specific database), which is a set of classes/ interfaces that implements these interfaces (such as java.sql.Driver) for a particular database system.


The JDBC API is comprised of two Java packages: java.sql and javax.sql.
  • java.sql:- This is the initial package that provides the API for accessing and processing data stored in a data source (usually a relational database) using the Java programming language.
  • javax.sql:- This is an extended package that provides the API for server-side data source access and processing from the Java programming language.

JDBC Classes, Interfaces And Exceptions

The following are core JDBC classes, interfaces, and exceptions in the java.sql package:
  • DriverManager:- This class loads JDBC drivers in memory. You can also use it to create java.sql.Connection objects to data sources (such as Oracle, MySQL, and so on).
  • Connection:- This interface represents a connection with a data source. You can use the Connection object for creating Statement, PreparedStatement, and CallableStatement objects.
  • Statement:- This interface represents a static SQL statement. You can use it to retrieve ResultSet objects.
  • PreparedStatement:- This interface extends Statement and represents a precompiled SQL statement. You can use it to retrieve ResultSet objects.
  • CallableStatement:- This interface represents a database stored procedure. You can use it to execute stored procedures in a database server.
  • ResultSet:- This interface represents a database result set generated by using SQL's SELECT statement.
  • SQLException:- This class is an exception class that provides information on a database access error or other errors.

What Is A JDBC Driver

A JDBC Driver allows a Java application/client to communicate with a SQL database. A JDBC driver is a Java class that implements the JDBC's java.sql.Driver interface and understands how to convert program (and typically SQL) requests for a particular database. A Java program that uses the JDBC API loads the specified driver for a particular DBMS before it actually connects to a database.

Types Of Drivers

JDBC can use four types of drivers to connect to databases.

JDBC driver type 1

The type 1 driver translates its calls into ODBC calls .ODBC then interacts with the desired database. It is the most available but slowest type, and it works only on Microsoft Windows and Sun Solaris. There is only one driver in existence, sun.jdbc.odbc.JdbcOdbcDriver.

JDBC driver type 2

The type 2 driver translates its calls to the native (C, C++, Pascal, and so on) API calls of the desired database, which then call the desired database .For example, Oracle Call Interface (OCI) calls are used in developing Oracle's type 2 drivers. OCI programs are normally written in C or C++, although they can be written in almost any programming language. You will need a driver for each database and operating system combination. Performance is faster than type 4 drivers.

JDBC driver type 3

The type 3 driver is a multitier (n-tier) driver .It is database-independent unlike the type 1, 2, and 4 drivers. Type 3 drivers connect to an application server (such as WebLogic). The application server in turn connects to a database using a type 1, 2, or 4 driver. The user just specifies the type 3 driver's class name and a data source name to connect to; there is no need to change the client code when the back-end database changes.

JDBC driver type 4

The type 4 driver is for databases that have written their APIs in Java, not C or C++ .So, no translation is needed at runtime by the driver; it calls the database using its Java API. MySQL's Connector/J driver and Oracle's Thin driver are both type 4. Note that type 1, 2, and 4 are two-tier (client-server) drivers. In other words, there is no application server in the middle. You can use these drivers in typical client-server environments.

Type 1 Drivers In Details

The JDBC type 1 driver, also known as the JDBC-ODBC bridge, is a database driver implementation that employs the ODBC driver to connect to the database. The driver converts JDBC method calls into ODBC function calls. The bridge is usually used when there is no pure-Java driver available for a particular database.


Translates query obtained by JDBC into corresponding ODBC query, which is then handled by the ODBC driver.

Sun provides a JDBC-ODBC Bridge driver. sun.jdbc.odbc.JdbcOdbcDriver. This driver is native code and not Java, and is closed source.

Client -> JDBC Driver -> ODBC Driver -> Database

There is some overhead associated with the translation work to go from JDBC to ODBC.

  • Almost any database for which ODBC driver is installed, can be accessed.
  • A type 1 driver is easy to install.
  • Performance overhead since the calls have to go through the JDBC overhead bridge to the ODBC driver, then to the native db connectivity interface.
  • The ODBC driver needs to be installed on the client machine.
  • Considering the client-side software needed, this might not be suitable for applets.
  • Will not be suitable for internet applications.

Now, look at this program:-


import java.sql.*;
import java.io.*;
class jdbc1
        public static void main(String args[])
                Connection con;
                Statement stmt;
                ResultSet rs;
                String str;

                        System.out.println("Connection successful");
                        rs=stmt.executeQuery("select * from student");

                catch(Exception ex)

Steps Used In The Above Program

The first thing to do is to import the packages or classes you will be using in the new class. The classes in our examples all use the java.sql package , which becomes available when the following line of code precedes the class definition:

import java.sql.*;

The star ( * ) indicates that all of the classes in the package java.sql are to be imported. Importing a class makes it visible and means that you do not have to write out the fully qualified name when you use a method or field from that class. If you do not include " import java.sql.*; " in your code, you will have to write " java.sql. " plus the class name in front of all the JDBC fields or methods you use every time you use them. Note that you can import individual classes selectively rather than a whole package. Java does not require that you import classes or packages, but doing so makes writing code a lot more convenient.

Java application calls the JDBC library. JDBC loads a driver which talks to the database.

We can change database engines without changing database code.
  1. Loading a database driver:-

    In this step of the jdbc connection process, we load the driver class by calling Class.forName() with the Driver class name as an argument. Once loaded, the Driver class creates an instance
    of itself. A client can connect to Database Server through JDBC Driver. Since most of the Database servers support ODBC driver therefore JDBC-ODBC Bridge driver is commonly used. The return type of the Class.forName (String ClassName) method is "Class". Class is a class in java.lang package.

    try {
            Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); //Or any other driver
    catch(Exception x){
            System.out.println( "Unable to load the driver class!" );

  2. Establishing Database Connection:-

    The JDBC DriverManager class defines objects which can connect Java applications to a JDBC driver. DriverManager is considered the backbone of JDBC architecture. DriverManager class manages the JDBC drivers that are installed on the system. Its getConnection() method is used to establish a connection to a database. It uses a username, password, and a jdbc url to establish a connection to the database and returns a connection object. A jdbc Connection represents a session/connection with a specific database. Within the context of a Connection, SQL, PL/SQL statements are executed and results are returned. An application can have one or more connections with a single database.

    JDBC URL Example:: jdbc: <subprotocol>: <subname>
    Each driver has its own subprotocol .
    Each subprotocol has its own syntax for the source. We're using the jdbc odbc subprotocol, so the DriverManager knows to use the sun.jdbc.odbc.JdbcOdbcDriver.

      Connection con=DriverManager.getConnection(url,"loginName","Password")
      catch( SQLException x ){
                      System.out.println( "Couldn't get connection!" );

  3. Creating a JDBC Statement object

    Once a connection is obtained we can interact with the database. Connection interface defines
    methods for interacting with the database via the established connection. To execute SQL statements, you need to instantiate a Statement object from your connection object by using the createStatement() method.

    Statement stmt= con.createStatement();

    A statement object is used to send and execute SQL statements to a database.

    Three kinds of Statements:-

    Statement: Execute simple sql queries without parameters.
    Statement createStatement()
    Creates an SQL Statement object.

    Prepared Statement: Execute precompiled sql queries with or without parameters.
    PreparedStatement prepareStatement(String sql)
    returns a new PreparedStatement object. PreparedStatement objects are precompiled
    SQL statements.

    Callable Statement: Execute a call to a database stored procedure.
    CallableStatement prepareCall(String sql)
    returns a new CallableStatement object. CallableStatement objects are SQL stored procedure
    call statements.
  4. Executing a SQL statement with the Statement object, and returning a jdbc resultSet.

    Statement interface defines methods that are used to interact with database via the execution of SQL statements. The Statement class has three methods for executing statements:
    executeQuery(), executeUpdate(), and execute(). For a SELECT statement, the method to use is executeQuery . For statements that create or modify tables, the method to use is executeUpdate. Note: Statements that create a table, alter a table, or drop a table are all examples of DDL statements and are executed with the method executeUpdate. execute() executes an SQL statement that is written as String object.

    ResultSet provides access to a table of data generated by executing a Statement. The table rows are retrieved in sequence. A ResultSet maintains a cursor pointing to its current row of data. The next() method is used to successively step through the rows of the tabular results.

    ResultSetMetaData Interface holds information on the types and properties of the columns in a ResultSet. It is constructed from the Connection object.

Prepared Statement Example


import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;

public class PreparedStatementExample
        public static void main(String[] args)
                try {
                        /** Loading the driver*/
                        /** Getting Connection*/
                        Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/test","root","root");
                        /** Creating Statement*/
                        PreparedStatement pst = con.prepareStatement("insert into emp(id,name)values(?,?)");
                        int i= pst.executeUpdate();
                        System.out.println(i + " Record(s) Inserted");
                        /** Closing the Connection*/
                } catch (Exception e)

Callable Statement Example


import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Types;
public class CallableStatementExample
        public static void main(String[] args)
                        /** Loading the driver*/
                        /** Getting Connection*/
                        Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/test","root","root");
                        /** Creating Statement*/
                        CallableStatement call = con.prepareCall("call test.Test(?,?,?)");
                        System.out.println("The addition is "+call.getInt(3));
                catch (Exception e)

[note:- This topic will be continued later with some other advanced concepts and explanation.The practical aspect will be taken more care(like DSN:-database source name). Use of JDBC in JSP will also be explained. Thank you.:pleased:]

Continue to JDBC Basics - Part II

pankaj.sea 8Mar2010 10:24

Re: JDBC Basics - Part I
Nice work!

techgeek.in 8Mar2010 11:53

Re: JDBC Basics - Part I
Thanks a lot !!

fashionbop 12Mar2010 08:21

Re: JDBC Basics - Part I
Thank you for sharing.
It works.Basic and good suggestion.

shabbir 2Apr2010 09:12

Re: JDBC Basics - Part I
If you like this this article nominate it for Article of the month - Mar 2010

Balaji Reddy 26Mar2012 19:10

Re: JDBC Basics - Part I
Thanks !

All times are GMT +5.5. The time now is 04:11.