Dec 20, 2009

Connecting to a Database

To establish a connection with a database, you need to load the database specific driver by calling the forName() method of the class Class. For e.g. JDBC – ODBC Bridge driver is used to communicate with DBMS / RDBMS such as MS SQL, MS Access. You can load this driver like shown below.

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver")

The Java.sql package contains classes and interfaces that helps in connecting to a database, sending SQL statements to the database and processing query results.

The Connection Object

The Connection object represents a connection with the database. You may have several Connection objects in your application that connects one or more database. The getConnection() method from DriverManager class is used to establish a connection with the database. This method attempts to locate the driver that can connect to the database represented by the JDBC URL passed to the getConnection() method. The JDBC URL is a string that provides a way of identifying the database. A JDBC URL consists of three parts.

<protocol>:<subprotocol>:<subname>

<protocol> in a JDBC URL is always jdbc.

<subprotocol> is the name of the database connectivity mechanism. If the mechanism for retrieving the data is ODBC – JDBC bridge, then the subprotocol should be odbc.

<subname> is used to identify database. This is also known as data source name. This contains information about the location of the database server, database name, user name and password to be used to connect the database server and the log file name to be used to store lengthy queries and driver and statistics.

The Statement Object

You can use the Statement object to send simple queries to the database. The Statement object allows you to execute simple queries. It has the following methods that can be used for querying.

  • The executeQuery() method exectes a select query and returns a ResultSet object.
  • The executeUpadate() executes an SQL Insert, Update or Delete statement and returns an int value specifying the number of rows affected by the query or 0 if the query does not return any value.

A sample program that connects to a Database using JDBC.

import java.sql.*;

public class QueryApp

{

public static void main(String a[])

{

    try {

    Class.forName("sun.jdbc.JdbcOdbcDriver"); // Loads the driver

    Connection con = DriverManager.getConnection("jdbc:odbc:MyDsn","UserName","password"); //establishes the connection to a database.

    Statement stat=con.createStatement(); // Returns a statement object

    stat.executeQuery("Select * from tablename");

    } catch(Exception e) {

    System.out.println("Error"+e);

    }

}

}

The ResultSet Object

The ResultSet object provides you methods to access data from a table. Executing a SQL statement usually generates a ResultSet object. The ResultSet object maintains a cursor pointing to its current row of data. Initially a cursor is positioned before the first row. The next() method moves the cursor the next row. You can retrieve data from the ResultSet rows by calling the getXXX(int coln) method where XXX refers to the datatype of column name such as String, an Integer or a Float. And coln refers to column number in the result set. The following table illustrates some of the widely used getXXX() methods.

Method

Description

String getString(int column_number)

Returns the value in the specified column of the current row in the ResultSet object as a Srting object. This method is used with char(n) and varchar(n) data types of SQL.

int getInt(int column_number)

Returns the value in the specified column of the current row in the ResultSet object as a integer. This method is used with smallint, tinyint and int data types of SQL.

  

float getFloat(int column_number)

Returns the value in the specified column of the current row in the ResultSet object as a float type. This method is used with float and money data types of SQL.

  

Date getDate(int column_number)

Returns the value in the specified column of the current row in the ResultSet object java.sql.Date object. This method is used with datetime data types of SQL.

 
 


 

Sample Program

import java.sql.*;

public class QueryApp

{

public static void main(String a[])

{

    try {

    Class.forName("sun.jdbc.JdbcOdbcDriver"); // Loads the driver

    Connection con = DriverManager.getConnection("jdbc:odbc:MyDsn","UserName","password"); //establishes the connection to a database.

    Statement stat=con.createStatement(); // Returns a statement object

    ResultSet rs=stat.executeQuery("Select * from tablename");

While(rs.next()){

    System.out.println(rs.getString(2));

}

    } catch(Exception e) {

    System.out.println("Error"+e);

    }

}

}


 

Introduction to JDBC

JDBC stands for Java Database Connectivity. Imagine that you have given the task of developing an application for a store to enable the store owner to maintain the daily transactions. Java application needs to communicate with the Database to perform these tasks. Sun Microsystems has included JDBC API as a part of JDK to enable java applications to communicate with a database.

Features of JDBC

  1. JDBC contains a set of classes and interfaces that are used to connect to a database built using any DBMS / RDBMS submit SQL queries to a database, retrieves and process the results of SQL queries.
  2. JDBC is a low level interface in which select and update statements are called directly from with in java programs.
  3. JDBC can be used with both two tier and three architectures. In two tier architecture a java program invokes the methods of JDBC API, which in turn communicates with the database server. In three tier architecture, a java applet or HTML form submits the SQL queries to the middle tier server, the middle tier server in turn communicates with the database server.

JDBC Drivers

The following two issues have to be considered while using JDBC.

  1. Java applications cannot communicate directly with database to retrieve and store data. This is because a database server cannot understand Java statements. Hence you need a mechanism that translates Java statements to SQL statements.
  2. There are different kinds of DBMS/RDBMS products that are available in today. A Java application should be DBMS independent to communicate with all these products without any changes.

JDBC API uses a driver to address these issues. JDBC API takes care of converting Java commands to SQL statements. However to address specific database issues, each database vendor provides a driver along with their database. A java application invokes the methods of JDBC API to communicate with the database. JDBC API in turn uses the driver to communicate with the database.

JDBC API submits the queries to the JDBC driver. The JDBC driver in turn converts the queries to a form that a DBMS/RDBMS can understand. The JDBC also retrieves the results of SQL queries and converts it into JDBC API classes and objects that can be used by the application. Since the JDBC driver takes care of the interaction with the database, any changes made in the database do not affect the application.


 

  
 

There are several categories of JDBC drivers provided by different database vendors. They are,

  1. JDBC-ODBC bridge driver
  2. Native API partly Java driver and
  3. Native protocol pure Java driver / JDBC-Net pure Java driver

JDBC-ODBC bridge driver

DBMS / RDBMS such as MS Access and SQL server contain the ODBC driver embedded in to them. A java program cannot communicate directly with ODBC API, since the ODBC API is written in C language and make use of pointers and other constructs that java does not supports. Sun Microsystems provides a driver to communicate with ODBC data sources from JDBC. The JDBC-ODBC bridge driver translates the JDBC API to ODBC API.




Native API partly Java driver

Some DBMS/RDBMSs such as DB2 and Informix contains a JDBC driver supplied by he vendor. These JDBC drivers consist of classes that can be invoked directly by the JDBC API.

Native protocol pure Java driver / JDBC-Net pure Java driver

These drivers are used to connect a client application or Applet to a database over a TCP / IP connection.

JDBC Driver Manager

The JDBC Driver Manager is the back bone of the JDBC architecture. It maintains a list of drivers created by different Database vendors. It connects the Java application to the appropriate specified in the Java program.