Wednesday, August 20, 2014

Tomcat 7 connection pool with JNDI datasource and postgreSQL

1. Tomcat's content.xml

<Context>    <Resource name="jdbc/postgres" auth="Container"            type="javax.sql.DataSource" driverClassName="org.postgresql.Driver"            url="jdbc:postgresql://127.0.0.1:5432/mydb"            username="myuser" password="mypasswd" maxActive="20" maxIdle="10"  maxWait="-1"/>  </Context>

2. Web application's web.xml

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

2. Code

    Connection conn = null;
        try {
            InitialContext cxt = new InitialContext();
            DataSource ds = (DataSource) cxt.lookup( "java:/comp/env/jdbc/postgres" );
            conn = ds.getConnection();
           
                 ...

                ...   
                while(rs.next()) {
                ...
                ...

                }
                rs.close();
            }
            conn.close();
        } catch (NamingException e1) {
            e1.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        };

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.