jdbcjndi

How to close JNDI connection?


I am using JNDI for database connection. I have created a XML file in META-INF for connection.

<?xml version="1.0" encoding="UTF-8"?>
<!-- The contents of this file will be loaded for each web application -->
<Context crossContext="true">

    <!-- Default set of monitored resources -->
    <WatchedResource>WEB-INF/web.xml</WatchedResource>

    <Resource name="jdbc/myDB" auth="Container"
        type="javax.sql.DataSource"
        maxActive="100" maxIdle="30" maxWait="600000"
        username="root" 
        password="abc123" 
        driverClassName="com.mysql.jdbc.Driver"
        url="jdbc:mysql://localhost:3306/game"/>
</Context>

In java class I am using following code to get the connection

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

But, how can i close the connection?


Solution

  • The DataSource will be in charge of the management of the physical connection to the database. When you call con.close (which is a must), the physical connection will be back to the pool and set the connection in a sleep state. In case a connection is closed, the DataSource will be in charge to obtain a new connection, if possible.

    In short, you should not worry about closing the physical connection.