Introduction
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 languages.
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
database.
- 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.
Syntax: Class.forName(sun.jdbc.odbc.JdbcOdbcDriver);
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 method.
-
Connection to the Dbms: In the second step we have
to create a connection with the database. For this, we use the DriverManager class. There is a static method,getConnection("url","user
name","password") of DriverManager class.It takes three string type arguments and returns an object of Connection.
Syntax: Connection con =
DriverManager.getConnection("jdbc:odbc:mydsn","system","tiger");
-
Creating and executing a statement: Using a Connection we create statement by the method createStatement()
and get the object of Statement.
Syntax: Statement s=con.createStatement();
-
Processing data returned by Dbms: According to our the query we use the data returned by Dbms.
In this way, we connect a java program using the Jdbc.
Simple program for creating connection in Java
- import java.sql.*;
- class CreateConnection
- {
- public static void main(String s[])
- {
- try
- {
-
- Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
-
- Connection con = DriverManager.getConnection("jdbc:odbc:mydsn","System","tiger");
- if(con!=null)
- {
- System.out.println("Connection Successfull");
- }
- else
- {
- System.out.println("Connection could not be established");
- }
-
- conn.close();
- }
- catch(SqlException e)
- {
- System.out.println("Exception occured"+ e);
- }
- }
- }
After compilation and execution of
above program we get the output as:
Thank You.....