Showing posts with label jdbc. Show all posts
Showing posts with label jdbc. Show all posts

Monday, October 19, 2009

JDBC Connectivity

The JDBC ( Java Database Connectivity) API defines interfaces and classes for writing database applications in Java by making database connections. Using JDBC you can send SQL, PL/SQL statements to almost any relational database. JDBC is a Java API for executing SQL statements and supports basic SQL functionality. It provides RDBMS access by allowing you to embed SQL inside Java code. Because Java can run on a thin client, applets embedded in Web pages can contain downloadable JDBC code to enable remote database access.

Although JDBC was designed specifically to provide a Java interface to relational databases, you may find that you need to write Java code to access non-relational databases as well.
JDBC Architecture

Java application calls the JDBC library. JDBC loads a driver which talks to the database. We can change database engines without changing database code.

JDBC Basics - Java Database Connectivity Steps


Before you can create a java jdbc connection to the database, you must first import the

java.sql package.

import java.sql.*; The star ( * ) indicates that all of the classes in the package java.sql are to be imported.

Below is a list of classes and interfaces that are commonly used for writing JDBC code:

java.sql.Connection
java.sql.PreparedStatement
java.sql.ResultSet
java.sql.SQLException
java.sql.DriverManager
javax.sql.DataSource

Following are the classes / interfaces that will be used for doing a lookup for the DataSource in the servers context (JNDI Lookup).

javax.naming.Context
javax.naming.InitialContext
javax.naming.NamingException

Using Java there are two ways for connecting to a database. Either the DataManager class can be used or JNDI lookup can be done. JNDI lookup is mostly used in web based applications. Let us first look at how DataManager class can be used to connect to the database.



import java.sql.Connection;
import java.sql.Statement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.DriverManager;

public class TestDBConnectivity
{
public static void main(String argv[])
{
Connection con = null;
Statement stmt = null;
ResultSet rs = null;

String url = "jdbc:oracle:thin:@server:1521:TESTDB"
String sql = "Select count(*) as total from Books";
int totalBooks=0;

try
{
Class.forName("oracle.jdbc.driver.OracleDriver"); //load the driver
con = DriverManager.getConnection(url, "dbuser", "dbpasswd");
stmt = con.CreateStatement();
rs = stmt.executeQuery(sql);

if(rs.next())
totalBooks = rs.getInt("total");

System.out.println("Total number of books : " + total);
}
catch(ClassNotFoundException ex)
{System.out.println("ClassNotFoundException:\n"+ex);}
catch(SQLException ex)
{System.out.println("SQLException:\n"+ex);}
finally
{
try
{
stmt.close();
rs.close();
con.close();
}
catch(SQLException ex)
{System.out.println("SQLException:\n"+ex);}
}
}
}







Now, let us look at how JNDI lookup works. For a small tutorial on JNDI please visit here.










For using a JNDI lookup first a resource has to be defined which can be done in the '\META-INF\context.xml' file. A sample of the 'context.xml' file is shown below:










import java.sql.Connection;
import java.sql.SQLException;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;

public class DAGConnection
{
private DAGConnection(){}

public static java.sql.Connection getConnection()
{
Connection con=null;
Context ctx=null;
DataSource ds=null;
try
{
ctx = new InitialContext();
if(ctx == null)
{
System.out.println("Lookup failed!");
throw new RuntimeException("JNDI resource can not be found!");
}

ds = (DataSource) ctx.lookup("java:comp/env/jdbc/DBTEST");
if(ds==null)
{
System.out.println("DataSource could not be found!");
throw new RuntimeException("DataSource could not be found!");
}

con = ds.getConnection();
}
catch(NamingException ex)
{
System.out.println(ex);
return null;
}
catch(SQLException ex)
{
System.out.println(ex);
return null;
}

return con;
}
}





In the above example, the method getConnection() does a JNDI lookup and returns an object of type java.sql.Connection. Doing  JNDI lookup returns an object of type DataSource which in turn is used to create a connection to the database. You will need to place the JDBC drivers for the database in the classpath while using DriverManager and in the '\WEB-INF\lib' folder while doing a JNDI lookup.

Tuesday, August 11, 2009

Retrieving Automatically Generated Keys

Retrieving Automatically Generated Keys

Many DBMSs automatically generate a unique key field when a new row is inserted into a table. Methods and constants added in the JDBC 3.0 API make it possible to retrieve these keys, which is a two-step process. First the driver is alerted that it should make the keys available for retrieval. The second step is to access the generated keys by calling the Statement method getGeneratedKeys. The rest of this section explains these two steps more fully.
  1. Step One - Tell the driver that it should make automatically generated keys available for retrieval. This is done when an SQL statement is sent to the DBMS, which for Statement objects, is when the statement is executed. Three new versions of the method executeUpdate and three new versions of the method execute signal the driver about making automatically generated keys available. These six new methods take two parameters, the first being in all cases an SQL INSERT statement. The second parameter is either a constant indicating whether to make all generated keys retrievable (Statement.RETURN_GENERATED_KEYS or Statement.NO_GENERATED_KEYS) or an array indicating which specific key columns should be made retrievable. The array elements are either the indexes of the columns to be returned or the names of the columns to be returned.

    Note that although it is possible to use the method execute for executing a DML (Data Manipulation Language) statement, this method is generally reserved for executing CallableStatement objects that produce multiple return values.
    • For a PreparedStatement object, the SQL statement is sent to the DBMS to be precompiled when the PreparedStatement object is created with one of the Connection.prepareStatement methods. Thus, the driver is notified about making automatically generated keys retrievable via these methods.


  2. Step Two - After the driver has been notified about making automatically generated keys available for retrieval, the keys can be retrieved by calling the Statement method getGeneratedKeys. This method returns a ResultSet object, with each row being a generated key. If there are no automaticallty generated keys, the ResultSet object will be empty.
    The following code fragment creates a Statement object and signals the driver that it should be able to return any keys that are automatically generated as a result of executing the statement. The example then retrieves the keys that were generated and prints them out. If there are no generated keys, the printout says that there are none.
String sql = "INSERT INTO AUTHORS (LAST, FIRST, HOME) VALUES " +
"'PARKER', 'DOROTHY', 'USA', keyColumn";

int rows = stmt.executeUpdate(sql,
Statement.RETURN_GENERATED_KEYS);

ResultSet rs = stmt.getGeneratedKeys();


int rows = stmt.executeUpdate(sql,
Statement.RETURN_GENERATED_KEYS);

ResultSet rs = stmt.getGeneratedKeys();
if (rs.next())
{
ResultSetMetaData rsmd = rs.getMetaData();
int colCount = rsmd.getColumnCount();
do {
for (int i = 1; i <= colCount; i++)   
{   
String key = rs.getString(i);     
System.out.println("key " + i + "is " + key); 
} 
} 
while (rs.next();)   }
else  
{ System.out.println("There are no generated keys."); }
Instead of telling the driver to make all automatically-generated keys available, it is possible to tell the driver to make particular columns retrievable. The following code fragment uses an array of column indexes (in this case, an array with one element) to indicate which columns with an automatically-generated key should be made available for retrieval.
String sql = "INSERT INTO AUTHORS (LAST, FIRST, HOME) VALUES " +
"'PARKER', 'DOROTHY', 'USA', keyColumn";
int [] indexes = {4};
int rows = stmt.executeUpdate(sql, indexes);
The following code fragment shows a third alternative-supplying an array of column names to indicate which ResultSet columns to make available. In this case, the driver is told to make the automatically-generated key in the column AUTHOR_ID retrievable.
String sql = "INSERT INTO AUTHORS (LAST, FIRST, HOME) VALUES " +
"'PARKER', 'DOROTHY', 'USA', keyColumn";
String [] keyColumn = {"AUTHOR_ID"};
int rows = stmt.executeUpdate(sql, keyColumn);
The above has been taken from http://java.sun.com/j2se/1.4.2/docs/guide/jdbc/getstart/statement.html#1000569