Thursday, March 13, 2014
All those who are new to programming have dealt with data provided either from a file or command line. But you might ne in a situation where you have to store and access data from a persistent storage more easily and which is not a file, e.g. database. It fully depends on vendors and databse administrators how the data will be stored on the disk. It provides a much easier way to access and save data and coders dont have to think about storage. But before we go into saving and accessing data from a database, the first step is to create a connection with the databse from your java program. Here we will be using Oracle 11g Express edition as our database. We will use JDBC to obtain the connection.
JDBC Architecture

     Just as we need a device driver to use a hardwarte from a software, similarly we will need a driver to access the database. There are different types of drivers : type 1, type 2 , type 3 and type 4. For more about this visit Wikipedia JDBC driver . We will be using type 4 JDBC driver which is completely written in Java. If you have already installed Oracle you will find that in
C:/oraclexe/app/oracle/product/11.2.0/server/jdbc/lib/ojdbc6.jar
Place that jar file in your classpath. Below is the code which will return the Connection object to the database
-------------------------------------------------------------------------------------------------------------------------
Java Source Code
-------------------------------------------------------------------------------------------------------------------------
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public final class Provider {
 static{
  try {
   Class.forName("oracle.jdbc.OracleDriver");
   System.out.println("Driver loaded successfully");
  } catch (ClassNotFoundException e) {
   System.out.println("Failed to load driver");
  }
 }
 
 public static Connection getCon(String userid, String pass) throws SQLException{
  return DriverManager.getConnection(
    "jdbc:oracle:thin:@localhost:1521:xe", userid, pass);
 }
}


This is the fisrt and foremost step of using JDBC. Happy coding :)

0 comments:

Post a Comment

Total Pageviews

Subscribe via Email

Followers


Popular Posts

About Me

My photo

I am a student of BTech Computer Science Engineering from RCCIIT,Kolkata. I am a crazy lover of Java and wants to settle as a Java developer. I have a seven years Java experience with an application developer experience for 2 years. Recently from March 2012 I am a registered S40 app developer for Nokia and has corrected an app of them. I am currently writing blogs to encourage and grow interest in all those who don't know or learning Java.