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();
student.setName("Amitabh");
        
try{
   //Load the database driver class
   Class.forName("org.hsqldb.jdbcDriver");
   }catch(ClassNotFoundException cfe){
       System.out.println("Driver not found");
       System.exit(0);
  }
        
Connection conn = null;
PreparedStatement stmt = null;
try{
   //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
   stmt.execute();
   }catch(SQLException se){
        System.out.println("Problem with data insert");
   } finally{
       //Make sure everything is closed
       try{
           if(stmt != null) 
             {
                stmt.close();
              }
           if(conn != null)
             {
                conn.close();
             }
       }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