Tomcat How To Configure Oracle DataSource And Do JNDI Lookup

Do you like this?

Summary:
The following snippet shows you how to configure Oracle data source in Tomcat and how to do JNDI lookup


Content:

Add the following snippet into <tomcat-home>\conf\context.xml

<Resource name="jdbc/test" auth="Container"            
		type="oracle.jdbc.pool.OracleDataSource"
		factory="oracle.jdbc.pool.OracleDataSourceFactory"
		driverClassName="oracle.jdbc.OracleDriver"
		url="jdbc:oracle:thin:@server:1521:db"
		user="" password="" /> 
		
Java Lookup Code:
  public void init() {
    try{
      Context ctx = new InitialContext();
      if(ctx == null ) 
          throw new Exception("Boom - No Context");

      DataSource ds = 
            (DataSource)ctx.lookup(
               "java:comp/env/jdbc/test");

      if (ds != null) {
        Connection conn = ds.getConnection();
              
        if(conn != null)  {
            foo = "Got Connection "+conn.toString();
            Statement stmt = conn.createStatement();
            ResultSet rst = 
                stmt.executeQuery(
                  "select id, foo, bar from testdata");
            if(rst.next()) {
               foo=rst.getString(2);
               bar=rst.getInt(3);
            }
            conn.close();
        }
      }
    }catch(Exception e) {
      e.printStackTrace();
    }
 }

 
comments powered by Disqus