JDBC


JAVA DATABASE CONNECTIVITY


What a JDBC is?

Java Database Connectivity (JDBC) is an application programming interface (API) for the programming language Java, which defines how a client may access a database. It is a Java-based data access technology used for Java database connectivity. It is part of the Java Standard Edition platform, from Oracle Corporation. It provides methods to query and update data in a database, and is oriented toward relational databases. A JDBC-to-ODBC bridge enables connections to any ODBC-accessible data source in the Java virtual machine (JVM) host environment.


History

The JDBC Project was started in January, 1996 and the specification was frozen in June, 1996 to seek the input of industry database vendors to insure that JDBC would be widely accepted upon its release. JDBC draws heavily from the ANSI SQL-92 stand ard. This does not imply that a JDBC driver must implement every SQL-92 function, it may implement a subset of the whole. Now comes the confusing point; while JDBC draws heavily from SQL-92 it is based on the X/Open SQL Call Level Interface (CLI). If it’s easier, you can think of the CLI as a SQL wrapper. One should note here that Microsoft’s ODBC is also based on the X/Open SQL CLI.


Why Should We Use JDBC?

Before JDBC, ODBC API was the database API to connect and execute the query with the database. But, ODBC API uses ODBC driver which is written in C language (i.e. platform dependent and unsecured). That is why Java has defined its own API (JDBC API) that uses JDBC drivers (written in Java language).

We can use JDBC API to handle database using Java program and can perform the following activities:

1. Connect to the database

2. Execute queries and update statements to the database

3. Retrieve the result received from the database.


Architecture of JDBC

JDBC API supports two-tier as well as three-tier processing models for availing database access. However, generally speaking, Its Architecture has two layers listed below:

1. JDBC API: This layer supports the connection to application-to-JDBC Manager. It makes use of the driver manager as well as database-specific drivers so as to give transparent connectivity to databases that are heterogeneous.

2. JDBC Driver API: This layer provides the connection of JDBC Manager to Driver. This driver manager makes sure that the correct driver is being used in accessing each of the data sources. It is also capable of supporting many concurrent drivers that are connected to various heterogeneous databases.

Java Database Connectivity with 5 Steps

There are 5 steps to connect any java application with the database using JDBC. These steps are as follows:

  1. Register the Driver class
  2. Create connection
  3. Create statement
  4. Execute queries
  5. Close connection

1) Register the driver class

The forName() method of Class class is used to register the driver class. This method is used to dynamically load the driver class.

Syntax of forName() method

1. public static void forName (String className) throws ClassNotFoundException  

Example to register the OracleDriver class

Here, Java program is loading oracle driver to esteblish database connection.

  • Class.forName("oracle.jdbc.driver.OracleDriver");  

 

2) Create the connection object

The getConnection() method of DriverManager class is used to establish connection with the database.

Syntax of getConnection() method

  • 1) public static Connection getConnection(String url)throws SQLException  
  • 2) public static Connection getConnection(String url,String name,String password)  
  • throws SQLException  

Example to establish connection with the Oracle database

  • Connection con=DriverManager.getConnection(  
  • "jdbc:oracle:thin:@localhost:1521:xe","system","password");  

 

 3) Create the Statement object

The createStatement() method of Connection interface is used to create statement. The object of statement is responsible to execute queries with the database.

Syntax of createStatement() method

  • public Statement createStatement()throws SQLException  

Example to create the statement object

  • Statement stmt=con.createStatement();  

 

4) Execute the query

The executeQuery() method of Statement interface is used to execute queries to the database. This method returns the object of ResultSet that can be used to get all the records of a table.

Syntax of executeQuery() method

  • public ResultSet executeQuery(String sql)throws SQLException  

Example to execute query

  • ResultSet rs=stmt.executeQuery("select * from emp");  
  • while(rs.next()){  
  •     System.out.println(rs.getInt(1)+" "+rs.getString(2));  
  • }  

 

5) Close the connection object

By closing connection object statement and ResultSet will be closed automatically. The close() method of Connection interface is used to close the connection.

Syntax of close() method

  • public void close()throws SQLException  

Example to close connection

1. con.close();  

It avoids explicit connection closing step.


JDBC Driver

JDBC Driver is a software component that enables java application to interact with the database.

The JDBC classes are contained in the Java Package java.sql and javax.sql.

JDBC helps you to write Java applications that manage these three programming activities:

1. Connect to a data source, like a database.

2. Send queries and update statements to the database

3. Retrieve and process the results received from the database in answer to your query

Structure of JDBC 

  


There are 4 types of JDBC drivers:

  1. JDBC-ODBC bridge driver
  2. Native-API driver (partially java driver)
  3. Network Protocol driver (fully java driver)
  4. Thin driver (fully java driver)

1) JDBC-ODBC bridge driver

The JDBC-ODBC bridge driver uses ODBC driver to connect to the database. The JDBC-ODBC bridge driver converts JDBC method calls into the ODBC function calls. This is now discouraged because of thin driver.


Oracle does not support the JDBC-ODBC Bridge from Java 8. Oracle recommends that you use JDBC drivers provided by the vendor of your database instead of the JDBC-ODBC Bridge.

Advantages:

  • easy to use.
  • can be easily connected to any database.

Disadvantages:

  • Performance degraded because JDBC method call is converted into the ODBC function calls.
  • The ODBC driver needs to be installed on the client machine.


2) Native-API driver

The Native API driver uses the client-side libraries of the database. The driver converts JDBC method calls into native calls of the database API. It is not written entirely in java.

 


Advantage:

  • performance upgraded than JDBC-ODBC bridge driver.

Disadvantage:

  • The Native driver needs to be installed on the each client machine.
  • The Vendor client library needs to be installed on client machine.


3) Network Protocol driver

The Network Protocol driver uses middleware (application server) that converts JDBC calls directly or indirectly into the vendor-specific database protocol. It is fully written in java.

Advantage:

  • No client side library is required because of application server that can perform many tasks like auditing, load balancing, logging etc.

Disadvantages:

  • Network support is required on client machine.
  • Requires database-specific coding to be done in the middle tier.
  • Maintenance of Network Protocol driver becomes costly because it requires database-specific coding to be done in the middle tier.


4) Thin driver

The thin driver converts JDBC calls directly into the vendor-specific database protocol. That is why it is known as thin driver. It is fully written in Java language.

Advantage:

  • Better performance than all other drivers.
  • No software is required at client side or server side.

Disadvantage:

  • Drivers depend on the Database.


When to use which Driver?

  1. If you are accessing one type of database, such as Oracle, Sybase, or IBM, the preferred driver type is type-4.
  2. If your Java application is accessing multiple types of databases at the same time, type 3 is the preferred driver.
  3. Type 2 drivers are useful in situations, where a type 3 or type 4 driver is not available yet for your database.
  4. The type 1 driver is not considered a deployment-level driver, and is typically used for development and testing purposes only.


Advantages and Disadvantages of JDBC

Advantages

Some of the advantages of using mentioned below:

1. It is capable of reading any database. The only requirement for it to do so is the proper installation of all the drivers.

2. It automatically creates the XML format of data from the database.

3. It does not require the content to be converted.

4. It provides full support to query and stored procedure.

5. It provides support to both Synchronous and Asynchronous processing.

6. It supports modules.

Disadvantages

Just like most of the API’s, It also has some cons. Some of these disadvantages are mentioned below:

1. It is very sensitive when it comes to the driver. Hence, it is very important to install correct drivers and to deploy them for each type of database in order to make use of it. This is a time taking task and challenging at times.

2. It does not allow a single sequence to update or insert multiple tables.


Sample Code

This sample example can serve as a template when you need to create your own JDBC application in the future.

This sample code has been written based on the environment and database setup done based on the above information.

Copy and paste the following example in FirstExample.java, compile and run as follows −

//STEP 1. Import required packages

import java.sql.*;

public class FirstExample {

   // JDBC driver name and database URL

   static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";  

   static final String DB_URL = "jdbc:mysql://localhost/EMP";

   //  Database credentials

   static final String USER = "username";

   static final String PASS = "password";

   public static void main(String[] args) {

   Connection conn = null;

   Statement stmt = null;

   try{

      //STEP 2: Register JDBC driver

      Class.forName("com.mysql.jdbc.Driver");

      //STEP 3: Open a connection

      System.out.println("Connecting to database...");

      conn = DriverManager.getConnection(DB_URL,USER,PASS);

      //STEP 4: Execute a query

      System.out.println("Creating statement...");

      stmt = conn.createStatement();

      String sql;

      sql = "SELECT id, first, last, age FROM Employees";

      ResultSet rs = stmt.executeQuery(sql);

      //STEP 5: Extract data from result set

      while(rs.next()){

         //Retrieve by column name

         int id  = rs.getInt("id");

         int age = rs.getInt("age");

         String first = rs.getString("first");

         String last = rs.getString("last");

         //Display values

         System.out.print("ID: " + id);

         System.out.print(", Age: " + age);

         System.out.print(", First: " + first);

         System.out.println(", Last: " + last);

      }

      //STEP 6: Clean-up environment

      rs.close();

      stmt.close();

      conn.close();

   }catch(SQLException se){

      //Handle errors for JDBC

      se.printStackTrace();

   }catch(Exception e){

      //Handle errors for Class.forName

      e.printStackTrace();

   }finally{

      //finally block used to close resources

      try{

         if(stmt!=null)

            stmt.close();

      }catch(SQLException se2){

      }// nothing we can do

      try{

         if(conn!=null)

            conn.close();

      }catch(SQLException se){

         se.printStackTrace();

      }//end finally try

   }//end try

   System.out.println("Goodbye!");

}//end main

}//end FirstExample

Now let us compile the above example as follows −

C:\>javac FirstExample.java

C:\>

When you run FirstExample, it produces the following result −

C:\>java FirstExample

Connecting to database...

Creating statement...

ID: 100, Age: 18, First: Zara, Last: Ali

ID: 101, Age: 25, First: Mahnaz, Last: Fatma

ID: 102, Age: 30, First: Zaid, Last: Khan

ID: 103, Age: 28, First: Sumit, Last: Mittal

C:\>


References:

https://en.m.wikipedia.org/wiki/Java_Database_Connectivity#:~:text=Java%20Database%20Connectivity%20(JDBC)%20is,Edition%20platform%2C%20from%20Oracle%20Corporation.

https://condor.depaul.edu/elliott/513/projects-archive/DS513Fall98/project/Chess/JDBC.html

https://www.javatpoint.com/java-jdbc

https://www.google.com/amp/s/www.geeksforgeeks.org/jdbc-drivers/amp/

https://www.educba.com/what-is-jdbc/


Created by:

Gajendra Jangid

Dhruv Jain

Spandan Hiwarkhede

Deepak Jadhav

Vedant Jathe

Comments

Post a Comment

Popular posts from this blog

Investment Decisions