Friday, June 27, 2008

What Is JDBC?

JDBC™ is an API developed by Sun Microsystems that provides a standard way to access data using the Java™ programming language. Using JDBC, an application can access a variety of databases and run on any platform with a Java Virtual Machine. It isn't necessary to write separate applications to access different database systems (Oracle and Postgres etc). Using JDBC allows you to write one application that can send SQL statements to different database systems. SQL is the standard language for accessing relational databases.The JDBC API defines a set of Java interfaces that encapsulate major database functionality, such as running queries, processing results, and determining configuration information. Because JDBC applications are written in Java, applications work on any platform.


To connect to a databse and perform operation on database one needs database driver which can communicate with database and perform db ooperations. There are 4 types of JDBC drivers. Sample program to connect to database using type-4 driver (Pure java driver i.e. driver written in java) -

To connect to oracle database we should know HOSTNAME of DB, SID, USER ID and PASSWORD. This information is mandatory to connect to a db and it can be used to create connection string.

To establish a connection to database and get information we should perform following steps -

1. Load driver class - Using Class.forName("driver class name"). As per JDBC specification Driver class should register itself with the DriverManager. Most of the Driver class have a static block, that block have the code to register itself with the DriverManager using DriverManager.registerDriver (driver).

2. DriverManager.getConnection("URL", "UID",PASSWORD) - This will search for the suitable driver for given connection string. DriverManager calls driver.acceptsURL(url) for each loaded driver. If it founds a suitable driver it will call driver.connect() e.g. URL format is jdbc:subprotocol:subname

3. Perform SQL operation

4. connection.closeConnection()


e.g to create connection and execute sample query on oracle database using type-4 driver-

Class.forName("oracle.jdbc.driver.OracleDriver");

Connection con =

DriverManager.getConnetion("jdbc:oracle:thin:@hostname:1521:SID","username","password");

Statement stmt = con.createStatement();

ResultSet rs = stmt.executeQuery("Select * from employee" );

while (rs.next () ){
System.out.println (rs.getString("empName"));
}
rs.close();
stmt.close();
con.close();

Keep in mind above three close statements throws checked exception (SQLException). That exception should be handled by the developer of the class.