Discussions

Web tier: servlets, JSP, Web frameworks: Multiple datasources in Tomcat 5

  1. Multiple datasources in Tomcat 5 (2 messages)

    I am running Tomcat 5.0.24 and need my app to be able to connect to multiple databases. Is it possible to use mutiple datasources in Tomcat ? In my context XML file, do I have to have a <Resource> tag for each datasource I want to connect to?
  2. I do have the same problem[ Go to top ]

    hello sir
    I am sorry to say that I do have the same problem.
    If u have got the answer by please give the solution to me too.
    Thank u
  3. Multiple datasources in Tomcat 5[ Go to top ]

    I am running Tomcat 5.0.24 and need my app to be able to connect to multiple databases. Is it possible to use mutiple datasources in Tomcat ? In my context XML file, do I have to have a <Resource> tag for each datasource I want to connect to?

    That's just the way it is : for each database you want to connect to, you have to declare a datasource in your server.xml file :

    <Resource name="jdbc/dsOne" auth="Container" type="javax.sql.DataSource"/>
      <ResourceParams name="jdbc/dsOne">
        <parameter>
    [...]
      </ResourceParams>
    <Resource name="jdbc/dsTwo" auth="Container" type="javax.sql.DataSource"/>
      <ResourceParams name="jdbc/dsTwo">
        <parameter>
    [...]
      </ResourceParams>

    Then, configure your web.xml :

    <resource-ref>
     <description>Oracle Datasource example</description>
     <res-ref-name>jdbc/dsOne</res-ref-name>
     <res-type>javax.sql.DataSource</res-type>
     <res-auth>Container</res-auth>
    </resource-ref>

    <resource-ref>
     <description>Oracle Datasource example</description>
     <res-ref-name>jdbc/dsTwo</res-ref-name>
     <res-type>javax.sql.DataSource</res-type>
     <res-auth>Container</res-auth>
    </resource-ref>

    Finally, access your datasource in your code :

    Context initContext = new InitialContext();
    Context envContext = (Context)initContext.lookup("java:/comp/env");
    DataSource ds = (DataSource)envContext.lookup("jdbc/dsOne");
    Connection conn = ds.getConnection();

    You will find more details in tomcat documentation on http://jakarta.apache.org/tomcat/tomcat-4.1-doc/jndi-datasource-examples-howto.html

    Hope this helps.