In order to obtain a Datasource, which is already created in the websphere application server; you have to first update the web.xml entry of your web application with the below lines:
<resource-env-ref id="ResourceEnvRef_1309162527015">
<description>ref data source alias</description>
<resource-env-ref-name>refDataSource</resource-env-ref-name>
<resource-env-ref-type>javax.
sql.DataSource
</resource-env-ref-type>
</resource-env-ref>
_____________________________________________________________
Once you update the web.xml entry use the below java code to obtain the data source:
public
class GetConnection {
public static void main(String args[]){
// getJNDIConnection();
// getConnection();
getJNDIConnection();
}
/** Uses JNDI and Datasource (preferred style). */
static Connection getJNDIConnection(){
String DATASOURCE_CONTEXT =
"refDataSource";
Connection result =
null;
try {
Context initialContext =
new InitialContext();
if ( initialContext == null){
System.
out.println("JNDI problem. Cannot get InitialContext.");
}
DataSource datasource = (DataSource)initialContext.lookup(DATASOURCE_CONTEXT);
if (datasource != null) {
result = datasource.getConnection();
}
else {
System.
out.println("Failed to lookup datasource.");
}
}
catch ( NamingException ex ) {
System.
out.println("Cannot get connection: " + ex);
}
catch(SQLException ex){
System.
out.println("Cannot get connection: " + ex);
}
return result;
}
}