Tuesday, June 29, 2010

Create a DB2 Data Source in JBOSS access it programmetically outside JBOSS context.

Problem Description:

It was a long lasting pain which only sufferers understand!!


Solution:
Just follow the steps mentioned one by one ...

1.We begin by adding its driver to the CLASSPATH: copy db2java.zip to the /server/default/lib directory. To configure the JBoss server with the DB2 data source, copy /docs/examples/jca/db2-ds.xml to the /server/default/deploy directory.

2.Next we modify the db2-ds.xml configuration file, by setting to

COM.ibm.db2.jdbc.app.DB2Driver and to jdbc:db2:, where is the DB2 database name.

Here it is start of db2-ds.xml

################################

"



test

false

jdbc:db2:tset

COM.ibm.db2.jdbc.app.DB2Driver

db2admin

db2admin

2

SELECT * FROM TEST.USER_TABLE

DB2


"

####################################

!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

PLEASE NOTE :In the above file I have one entry

false

It is kept false for connecting to JBoss Datasource from a standalone client.

!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

3.Remove hsqldb-ds.xml from /server/default/deploy

4.Go to jboss-4.2.0.GA\server\default\conf\standardjbosscmp-jdbc.xml

Then we modify standardjaws.xml (or jaws.xml) to set and .

java:/lkrgt

DB2

5.Now We need to test the data source from a Java class .

Copy all jar files from jboss-4.2.0.GA\client and place to lib or add to class path



Sample code:

package com.ayan;

import java.sql.Connection;

import java.sql.ResultSet;

import java.sql.Statement;

import java.util.Hashtable;


import javax.naming.InitialContext;

import javax.sql.DataSource;


public class TestConnect

{

public static void main(String[] args)

{

try

{

final String sql = "select * from LKRGT.TRAINING_REQUEST ";

Hashtable ht=new Hashtable();

ht.put(InitialContext.INITIAL_CONTEXT_FACTORY,

"org.jnp.interfaces.NamingContextFactory");

ht.put(InitialContext.PROVIDER_URL,"jnp://localhost:1099");

ht.put(InitialContext.URL_PKG_PREFIXES,"org.jboss.naming:org.jnp.interfaces");

InitialContext ic=new InitialContext(ht);

if(ic!=null)

{

System.out.println("Initial Context success");

}

DataSource ds=(DataSource)ic.lookup("lkrgt");

if(ds!=null)

{

System.out.println("Data Source success");

}

Connection con = null;

Statement stmt = null;

ResultSet rs = null;

try

{

con = ds.getConnection();

stmt = con.createStatement();

rs = stmt.executeQuery(sql);

while(rs.next()) {

System.out.println("Query '" + sql + "' returned " + rs.getString(1));

}

}

finally

{

if(rs != null)

rs.close();

if(stmt != null)

stmt.close();

if(con != null)

con.close();

}

}

catch (Exception e)

{

e.printStackTrace();

}

}


}



No comments:

Post a Comment