Created
July 5, 2016 12:49
-
-
Save danieltnaves/5de9e126bafa1c275586ce1af467d81d to your computer and use it in GitHub Desktop.
Connecting Tomcat 8 Data Source (Oracle)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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
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>