title: Obtaining connection to database in JBoss?
body: <p>This is my jboss/deploy/postgres-ds.xml file. The connection url, username and password is given here. How do I obtain a connection to this database in my servlet. </p>
  
  <pre><code>&lt;local-tx-datasource&gt;
          &lt;jndi-name&gt;PostgresDS&lt;/jndi-name&gt;
          &lt;connection-url&gt;jdbc:postgresql://localhost:5432/postgres&lt;/connection-url&gt;
          &lt;driver-class&gt;org.postgresql.Driver&lt;/driver-class&gt;
          &lt;user-name&gt;postgres&lt;/user-name&gt;
          &lt;password&gt;qwerty&lt;/password&gt;
              &lt;!-- sql to call when connection is created
              &lt;new-connection-sql&gt;some arbitrary sql&lt;/new-connection-sql&gt;
              --&gt;
  
              &lt;!-- sql to call on an existing pooled connection when it is obtained from pool 
              &lt;check-valid-connection-sql&gt;some arbitrary sql&lt;/check-valid-connection-sql&gt;
              --&gt;
  
            &lt;!-- corresponding type-mapping in the standardjbosscmp-jdbc.xml (optional) --&gt;
  
        &lt;/local-tx-datasource&gt;
  </code></pre>
  
  <p>Should I obtain the connection like this in every servlet : </p>
  
  <pre><code>Connection conn =null; // Create connection object
          String database = "postgres"; // Name of database
          String user = "postgres"; //
               String password = "qwerty";
               String url = "jdbc:postgresql://localhost:5432/" + database;
  ResultSet rs = null;
               ResultSetMetaData rsm = null;  
   try{
  Class.forName("org.postgresql.Driver").newInstance();
  //.newInstance()
  } catch(Exception e) 
     {
  System.err.println(e);
  }
  
  try{
  conn = DriverManager.getConnection(url, user, password);
  
  }catch(SQLException se) 
  {
  System.err.println(se);
  }
  </code></pre>
  
  <p>If this has to be done everytime, then why give the url, username and password in the postgres-ds.xml file?</p>