Java – Obtaining connection to database in JBoss

javajbosspostgresqlservlets

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.

<local-tx-datasource>
        <jndi-name>PostgresDS</jndi-name>
        <connection-url>jdbc:postgresql://localhost:5432/postgres</connection-url>
        <driver-class>org.postgresql.Driver</driver-class>
        <user-name>postgres</user-name>
        <password>qwerty</password>
            <!-- sql to call when connection is created
            <new-connection-sql>some arbitrary sql</new-connection-sql>
            -->

            <!-- sql to call on an existing pooled connection when it is obtained from pool 
            <check-valid-connection-sql>some arbitrary sql</check-valid-connection-sql>
            -->

          <!-- corresponding type-mapping in the standardjbosscmp-jdbc.xml (optional) -->

      </local-tx-datasource>

Should I obtain the connection like this in every servlet :

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);
}

If this has to be done everytime, then why give the url, username and password in the postgres-ds.xml file?

Best Answer

you can use DataSource to get Connection like

javax.naming.Context ic = new javax.naming.InitialContext();
javax.naming.Context ctx = (javax.naming.Context) ic.lookup("java:");
javax.sql.DataSource ds = (javax.sql.DataSource) ctx.lookup("PostgresDS");
java.sql.Connection con = ds.getConnection();
Related Topic