JDBC Introduction and sample connection

JDBC or Java Data Base Connectivity is an open specification. As part of this specification JavaSoft has provided some classes like
  • java.sql.DriverManager
  • java.sql.Types
  • java.sql.Date
  • java.sql.Time
  • java.sql.TimeStamp
It also provides a set of interfaces like Connection, Driver, Statement, ResultSet etc
A JDBC driver is a set of classes that provide the implementation of the above interfaces specified as part of JDBC API. Several companies have provided the implementation of JDBC driver. For example, Oracle provides driver in the form of "classes12.jar". Diver manager is responsible for managing the drivers. As part of JDBC DriverManager id provided as a class.
Question: Connection is an interface. How can you create an object to Connection interface?
Answer: We cannot directly create an object to Connection interface. When we execute Connection c = DriverManager.getConnection(); it internally executes the code that is provided by JDBC driver vendor. This code creates an object based on the class provided by the vendor that implements connection interface.
Generic procedure for establishing connection with the data base
  • Register the driver.
  • Use DriverManager.getConnection method to establish the connection with the data base.
Below is a sample program to connect to Oracle data base. File: com.ram.app.ConnectionExample.java
package com.ram.app;

import java.sql.Connection;
import java.sql.Driver;
import java.sql.DriverManager;

public class ConnectionExample {
 public static void main(String[] args) throws Exception{
  Driver driver = new oracle.jdbc.driver.OracleDriver();
  DriverManager.registerDriver(driver);
  Connection conn = DriverManager.getConnection("dbc:oracle:thin:@localhost:1521:xe","hr","hr");
  System.out.println("Connected to :: "+conn.getClass());
 }
}

Execute ConnectionExample.java file. Output is given below.

No comments:

Post a Comment