The JDBC(Java Database Connectivity) API(Collection of classes
and interfaces) is a technique through which we connect our program to the
database smoothly. Java is one of the best languages that provides a connection
through to the database smoothly, in comparison to other language.
|Java Program ||--->JDBC Api ||--->Driver||--->||Database Source |
Figure 1: Description of the working of Jdbc
Steps of Jdbc for connecting the database
- Loading the Jdbc driver.
- Connection to the Dbms.
- Creating and executing a statement.
- Processing data returned by the Dbms
- Close the connection with the Dbms.
We have to import the sql package, which resides in the java .lang package for performing
these steps. After this step we have to write our code for connecting to any
In this way, we connect a java program using the Jdbc.
- Loading Jdbc Driver: In this step, we load the driver class at runtime which implements the Driver interface. In Java we use a class known as Class for loading any class at runtime .forName(Driver name in String) is the static method of class, Class is used to load any driver class at runtime. The return type of this method is an object of class ,Class.
The above line is used for loading any driver class at runtime. We
generally do not catch the value (Object of class,Class) returned by this
Connection to the Dbms: In the second step we have to create a connection with the database. For this we use the DriverManagerclass. There is a static method,getConnection("url","user name","password") of DriverManager class.It takes three string type arguments,and returns object of Connection.
Syntax: Connection con =
Creating and executing a statement: Using a Connection we create statement by the method createStatement() and get the object of Statement.
Processing data returned by Dbms: According to our query we use the data returned by Dbms.
Simple program for creating connection in Java
public static void main(String s)
con = DriverManager.getConnection("jdbc:odbc:mydsn","System","tiger");
System.out.println("Connection could not be established");
System.out.println("Exception occured"+ e);
After compilation and execution of
above program we get the output as: