Database Connectivity using Type I – JDBC Driver in Java(J2SE)

By August 15, 2015JAVA

What is JDBC?

JDBC(Java DataBase Connectivity) is used for connecting to different database by which user can shift from one database to another database very easily in platform independent manner. JDBC contains set of functions & specification in the form of packages i.e.:

  • java.sql.*–Core SQL Package
  • javax.sql.*–Extended SQL Package
  • JDBC Driver act like an interface between front end application and back end database.
  • There are four types of JDBC Driver
    • Type I-ODBC(Open DataBase Connectivity) Bridge Driver 
    • Type II-Java Native Interface Driver
    • Type III-Net Protocol Driver
    • Type-IV-Native Protocol Drover
  • Type I Driver, there exist an implementation class by which user can be able to connect to different database.
  • This implementation class, named JdbcOdbcDriver.class is provided within rt.jar file.
  • Connecting to any Database:-
    Step 1) Loading a Driver: 
    Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”);
    Step 2) Getting Connection: 
    Connection con = DriverManager.getConnection(““,”“,”“);

    Step 3) Create Statement Object:

    Statement st = con.createStatement();

    Step 4) Prepare a query and execute the query at backend database.

    • ResultSet rs = st.executeQuery(““);
    • boolean flag = st.execute(““);
    • int x = st.executeUpdate(““);

    Step 5) Close all connections: 

    st.close();

    con.close();

    Sample JDBC code for this demonstration:

    import java.sql.*;
    
    class DBConnectivity
    
    {
    
    public static void main( String [] args)
    
    {
    
    Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
    
    Connection conn = DriverManager.getConnection("jdbc:odbc:OracleDSN","scoot","tiger");
    
    Statement st = conn.createStatement();
    
    boolean flag = st.execute("create table student(ID varchar2(5), NAME varchar2(30), MARKS number(5))");
    
    int x = st.executeUpdate("inser into stud values('101','Pallavi',879)");
    
    ResultSet rs = st.executeQuery("<SELECT ID,NAME,MARKS from student>");
    
    while (re.nwex())
    
    {
    logout("ID:-"+rs.getString(1)+"\t");
    
    logout("NAME:-"+rs.getString(2)+"\t");
    
    logout("MARKS:-"+rs.getInt(3)+"\n");
    
    }
    
    }
    
    public void logout(String msg)
    
    {
    System.out.println(msg);
    }
    
    }
    

    Note: Here “OracleDSN” is User Created DSN (Data Source Name), in Administrative Tools–>Data Source

    Pankaj Singh Sugara

    Author Pankaj Singh Sugara

    Experienced Software Engineer with a demonstrated history of working in the marketing and advertising industry. Skilled in SQL, Web Applications, PHP, WordPress, and Joomla. Strong engineering professional with a B-TECH focused in Information Technology from JCDM College of Engineering Sirsa, Haryana.

    More posts by Pankaj Singh Sugara