Skip to content

Instantly share code, notes, and snippets.

@danieltnaves
Created July 5, 2016 12:49
Show Gist options
  • Save danieltnaves/5de9e126bafa1c275586ce1af467d81d to your computer and use it in GitHub Desktop.
Save danieltnaves/5de9e126bafa1c275586ce1af467d81d to your computer and use it in GitHub Desktop.
Connecting Tomcat 8 Data Source (Oracle)
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 DSConn {
public static Connection getConnection() throws SQLException, ClassNotFoundException, NamingException {
Context initContext = new InitialContext();
Context envContext = (Context)initContext.lookup("java:/comp/env");
DataSource ds = (DataSource)envContext.lookup("jdbc/OracleDS");
Connection conn = ds.getConnection();
System.out.println(conn);
return conn;
}
}
@danieltnaves
Copy link
Author

Eclipse issues

If you are using Eclipse with Tomcat to test Data Source, you will have to add extra context.xml inside META-INF folder. This happens because Eclipse overrides Tomcat's context file (remove this file in production enviroment).

More information: http://stackoverflow.com/questions/22376088/eclipse-overriding-jndi-resource-in-tomcat

image

File contents

<?xml version="1.0" encoding="UTF-8"?> <Context> <!-- Specify a JDBC datasource --> <Resource auth="Container" driverClassName="oracle.jdbc.driver.OracleDriver" maxActive="100" maxIdle="30" maxWait="-1" name="jdbc/OracleDS" type="javax.sql.DataSource" url="jdbc:oracle:thin:@host:port:SIDNAME" username="user" password="password" /> </Context>

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment