Saturday, 21 June 2014

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

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("<URL>","<UserName>","<Password>");
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("<SQL SELECT command>");
  • boolean flag = st.execute("<SQL Non-SELECT command>");
  • int x = st.executeUpdate("<SQL DML command>");

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

No comments: