Saturday, August 16, 2014

Java Database Connectivity (JDBC)

JDBC stands for Java Database connectivity. It's an API which helps Java based applications to interact with RDBMS using SQL and PL/SQL. JDBC is part of specification and defined the interfaces. The implementation is provided by the jdbc vendors. For example you will use a different JDBC driver for connecting to Oracle and DB2. However if you are writing your code against the JDBC base interfaces, the program is guaranteed to run against both the databased by just switching the implementation.

Let's look into a typical JDBC code

Student student = new Student();
   //Load the database driver class
   }catch(ClassNotFoundException cfe){
       System.out.println("Driver not found");
Connection conn = null;
PreparedStatement stmt = null;
   //Get the connection
   conn = DriverManager.getConnection ("jdbc:hsqldb:hsql://localhost","sa","");
   //Create a statement
   stmt = conn.prepareStatement ("insert into STUDENT (name) values (?) ");
   stmt.setString(1, student.getName());

   //Execute statement
   }catch(SQLException se){
        System.out.println("Problem with data insert");
   } finally{
       //Make sure everything is closed
           if(stmt != null) 
           if(conn != null)
       }catch(SQLException se) {

In a nutshell, the following steps are done
  • Define connection parameters
  • Open the connection
  • Specify the statement
  • Prepare and execute the statement
  • Process any exception
  • Close the connection
Many modern day applications use Spring with Hibernate to deal with database connectivity as they provide easy and maintainable way.

No comments:

Post a Comment